Axios and response data set split to multiple arrays - javascript

I'm trying to get data from an API using axios command like
function fetchData(apiURL){
let data = [];
let options = {
method: "GET",
url: apiURL,
headers: {
"Access-Control-Allow-Origin": "*"
},
credentials: "include"
};
axios(options)
.then(response => {
data = response.data;
console.log(data);
})
.catch(function (error) {
console.log("System error : " + error);
});
return data;
}
but that will produce sets of arrays which will store arrays of JSONs from response.data in count of 100 per array set.
I haven't had problem using fetch() to retrieve all data. How I can get similar response of one large array of JSON objects instead of a split?
PS.
I have triggered that function in the
componentDidMount() {
const apiURL = process.env.REACT_APP_API;
let tableData = fetchData(apiURL);
console.log("DATA " + JSON.stringify(tableData));
this.setState({tblData : tableData});
}

Axios requests are asynchronous and return promises, so you need to adjust your example a bit so that your function returns a promise.
/**
* #return {Promise<T>}
*/
function fetchData(apiURL){
const options = {
method: "GET",
url: apiURL,
headers: {
"Access-Control-Allow-Origin": "*"
},
credentials: "include"
};
return axios(options)
.then(response => {
return response.data;
})
}
Now, when you consume this API do so asynchronously.
function somethingThatUpdatesThatUI() {
fetchData("/api/foo/bar")
.then((data) => {
//perform updates to UI or state here
})
.catch((err) => {
//alert the users that an error has happened here
})
}

You can update the componentDidMount function:
componentDidMount() {
const apiURL = process.env.REACT_APP_API;
fetchData(apiURL).then(data => {
console.log(data ${JSON.stringify(tableData)})
this.setState({tblData : data});
})
}

Related

How to iterate json object after async fetching json in jQuery?

I have an issue with iterating json object in jQuery after fetching asynchronly.
With async function 'listFiles' I managed to succesfully get the desired filelist of directory (dir), at least console.log shows json with content.
But when I try to call $.each on fetched filelist json object, $.each simply doesn't work.
The console.log inside $.each function should output something.
async function listFiles(dir){
var json_data = await fetch('action.php', {
method: 'POST',
mode: "same-origin",
credentials: "same-origin",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({dir:dir})
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
return data
})
.catch((error) => {
console.error('Error:', error);
});
return json_data;
}
var json = listFiles('images');
$(() => {
$.each(json, function(index,val){ //this function doesn't work, dunno why :(
console.log("index: "+index+"; value: "+val);
})
console.log(json); //this shows fetched json object's content
});
You code should look something like below, you were using async-await and also using callbacks, and also you were printing data when it was not available.
async function listFiles(dir) {
try {
const response = await fetch('action.php', {
method: 'POST',
mode: "same-origin",
credentials: "same-origin",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ dir: dir })
})
const json_data = await response.json();
console.log('Success:', json_data);
return json_data;
}
catch (error) {
console.error('Error:', error);
}
}
async function printJsonData() {
var json = await listFiles('images');
$.each(json, function (index, val) { // now it should work :)
console.log("index: " + index + "; value: " + val);
})
console.log(json); //this shows fetched json object's content
}
printJsonData();

How can I use a state in a url to make a get using axios in reactjs

I am using axios in react to get information from a django backend, I am getting the user data and I am storing it in a state in the component but I want to use one of the attributes in the user_data state in the url of another get to get more information from the backend, I do not know if I explained it correctly but here is the code :
state = {
user_data: [],
classes: []
}
componentDidMount() {
const config = {
headers: {
'Content-Type': 'application/json',
'Authorization': `JWT ${localStorage.getItem('access')}`,
'Accept': 'application/json'
}
};
axios.get(`${process.env.REACT_APP_API_URL}/auth/users/me/`, config)
.then(
res => {
this.setState({
user_data: res.data
});
}
)
const myString = this.state.user_data.SectionNumber
axios.get(`${process.env.REACT_APP_API_URL}/Elearning/Classes/${myString}`, config)
.then(
res => {
this.setState({
classes: res.data
});
console.log(res.data);
}
)
}
I do not know how to change the state object into something that axios can understand and use in the url
At this point when you are fetching the user related data you do not need to depend on the state. You can pass the second call as a callback to the first setState so that it can update it when the promise resolves and state has been updated.
axios.get(`${process.env.REACT_APP_API_URL}/auth/users/me/`, config)
.then(
res => {
this.setState({
user_data: res.data
});
}, () => {
const myString = this.state.user_data.SectionNumber
axios.get(`${process.env.REACT_APP_API_URL}/Elearning/Classes/${myString}`, config)
.then(
res => {
this.setState({
classes: res.data
});
console.log(res.data);
}
)
}
)
You don't need to set the state and then take from the state to use this parameter in your url. You can use promises and pseudo-synchronous code async/await and it should help.
async componentDidMount() {
const config = {
headers: {
'Content-Type': 'application/json',
'Authorization': `JWT ${localStorage.getItem('access')}`,
'Accept': 'application/json'
}
};
const userDataResponse = await axios.get(`${process.env.REACT_APP_API_URL}/auth/users/me/`, config)
const myString = userDataResponse.data.SectionNumber;
const classesResponse = await axios.get(`${process.env.REACT_APP_API_URL}/Elearning/Classes/${myString}`, config)
this.setState({
user_data: userDataResponse.data,
classes: classesResponse.data
});
}
This is the code that worked with me
axios.get(`${process.env.REACT_APP_API_URL}/auth/users/me/`, config)
.then(
res => {
this.setState({
user_data: res.data
});
const SectionNumber = this.state.user_data.SectionNumber
axios.get(`${process.env.REACT_APP_API_URL}/Elearning/Classes/${SectionNumber}`, config)
.then(
res => {
this.setState({
classes: res.data
});
}
)
}
)
I am also facing a similar problem and i have done exactly as you have shown but I do not see the results.
axiosInstance.get('/user/profile/' + this.state.adminCard).then(response => {
axiosInstance.defaults.headers['Authorization'] = "JWT " + response.data.access;
this.setState({
fullName: response.data.lastName + ", " + response.data.firstName,
diploma: response.data.diploma,
projectSlug: response.data.project
})
}, () => {
const slug = this.state.projectSlug;
axiosInstance.get('/user/project/' + slug).then(response => {
axiosInstance.defaults.headers['Authorization'] = "JWT " + response.data.access;
this.setState({
assignedProjectName: response.data.projectName,
assignedProjectDesc: response.data.projectDesc,
assignedProjectSupervisor: response.data.projectSupervisor
})
console.log(this.state.assignedProjectName)
})
})
On the line where I console.log(this.state.assignedProjectName), I do not even get a return, please advice.

Searchbar in react to call table of data

I'm trying to create a searchbar in react that creates a table of data from an API inside the current view.
async function handleSearch() {
console.log("searching...", searchRef.current?.value);
setMessage("Searching...");
var headers = {
"Content-Type": "application/x-www-form-urlencoded",
"auth-token": token,
};
fetch(
"http:"..
{
method: "GET",
headers: headers,
}
)
.then((response) => {
setMessage("");
if (response.status !== 200) {
console.log("erROR", response);
return null;
} else {
console.log("success", response);
this.searched = true;
let productList = response.json()
return productList;
}
})
.then((responseData) => {
console.log("responseData", responseData);
// setting resonseData to productList
setProductList(responseData);
});
}
For some reason this is ridiculously hard to get working.
I would imagine the code above would work and fill the table with the correct array, but is it not.
The JSON response is like this and works properly in the console with the search component currently.
Any idea on how to solve this issue?
It seems you need to add productList as state variable like below.
// We need to initialize with empty array. Otherwise while rendering component for the first time it will try to access map of undefined(productList).
const [productList,setProductList] = useState([]);
// And then in your fetch call you can store data inside productList
fetch(
"http://localhost:5000/adverts/mwap?searchTerm=" +
encodeURIComponent(searchRef.current.value),
{
method: "GET",
headers: headers,
}
)
.then((response) => {
setMessage("");
if (response.status !== 200) {
console.log("erROR", response);
return null;
} else {
console.log("success", response);
this.searched = true;
let productList = response.json()
return productList;
}
})
.then((responseData) => {
console.log("responseData", responseData);
// setting resonseData to productList
setProductList(responseData);
});

Returned array from function - TypeError: callback is not a function

I am writing a simple js function to return an array of strings fetched using the fetch API. Whenever I try to run code, I get this error: TypeError: callback is not a function
This is my code
function getFlavors(franchise, callback) {
const fetch = require('node-fetch');
let flavors= [];
fetch('url', {
method: 'POST',
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify({ "franchise": franchise })
})
.then(res => res.json())
.then(json => {
json.forEach(element => {
flavors.push(element.flavor)
});
// console.log(flavors);
callback(flavors); <-- VALUES DISPLAYED ON CONSOLE
})
.catch(error => {
console.log(error);
})
}
let benJerrysFlavors = [];
getFlavors("ben&jerrys",benJerrysFlavors);
I am able to see the values on the console but when attempting to return the array from function, I get the callback error
Any ideas as to what might be the issue?
It should be called with a callback function passing the data to it. And you can uptate your array then with the returned data:
let benJerrysFlavors = [];
getFlavors("ben&jerrys", (ret) => {
benJerrysFlavors = ret;
});
Try to change from:
callback(flavors)
To:
callback.push(...flavors)

Unable to get fetch response on react native app

I am stuck on one of the mysterious issue. The problem goes like this:
What I Do??
Simply do login api call and if login success then I have to fetch amount of data from 5-6 api calls and store them in local database (Realm). Here is my code.
login(email, password) {
this.toggleLoadingFunction(true);
fetch(LoginURL, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: email,
password: password,
request_from: 'mobile'
}),
})
.then(async res => {
if (res.ok) {
let data = await res.json();
global.user = data['user']
global.token = data['token']
getAllMasterDataAndSaveInRealm().then(() => {
this.toggleLoadingFunction(false);
global.storage.save({ key: 'LoggedInData', data: data });
this.props.navigation.navigate('Project', data);
}).catch(() => {
this.toggleLoadingFunction(false);
Alert.alert("Master Data Failed !!!");
})
} else {
this.toggleLoadingFunction(false);
let data = await res.json();
Alert.alert("Login Failed!!!", data.message)
}
})
.catch(error => {
this.toggleLoadingFunction(false);
Alert.alert("Network Error. Please try again.")
})
Here getAllMasterDataAndSaveInRealm() is lies on helper function which calls 5-6 apis and response back if all work is done. Here is how it looks like:
export const getAllMasterDataAndSaveInRealm = () => {
const token = global.token;
return new Promise.all([
getMaterials(token),
getEquipments(token),
getObjective(token),
getCategories(token),
getNcData(token),
getPlans(token)]
);
}
Each function inside getAllMasterDataAndSaveInRealm() returns Promise after successfully stored data in local realm db. Here is one of the above function.
export const getActivityPlan = (token) => {
return new Promise((resolve, reject) => {
return fetch(FetchActivityPlanDataURL, {
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'access_token': `${token}`
}
}).then((response) => {
console.log("Activity Plans Api response", response);
return response.json()
})
.then((responseJson) => {
const { data } = responseJson
console.warn("Activity Plans Api", data);
global.realm.write(() => {
for (var item of data) {
item.id = item.id ? item.id : 0;
item.activity_id = item.activity_id ? item.activity_id.toString() : "";
item.activity_name = item.activity_name ? item.activity_name.toString() : "";
item.activity_cost = item.activity_cost ? item.activity_cost.toString() : "";
item.project_id = item.project_id ? item.project_id : 0;
global.realm.create("ActivityPlan", item, true);
}
})
resolve(data);
})
.catch((error) => {
reject(`Activity Plan Failed ${error}`)
});
})
}
All remaining functions are same as above ( what they do is simply fetch data from api and store it in realm and resolve or reject)
What I Expect:
getAllMasterDataAndSaveInRealm() function Just store all the required data in db and let me know all done and then navigate to the another screen, as Login and fetching data is done.
Problem:
When I do run the app and process for login, Sometimes it works fine but most of the time App stuck on showing loader since some of the api call among 6 api from above do not get response from the request ( I do log the response) on wifi. But when I use mobile data and VPN it always works.
When I log request on server console, response is sent with code 200, but app is unable to get response for the request.
I am new on react native. I do lots of searches over internet but unable to find the solution. I don't have any idea whats going wrong with the code. Please help me out.
Project Configurations:
"react": "16.8.6",
"react-native": "0.60.4",
"realm": "^2.29.2",
Node version: v9.0.0

Categories

Resources