I created this reactjs app.
In this app there is a singleton class "ServerMgr" that I use to send post request to my server.
Previously I used the js fetch function and it worked fine, but now I need to replace it with axios.
I replaced it but even if I set the async/await, it doesn’t wait for the await.
I explain the situation:
in App.js there is this useEffect triggered when the component is mounted that after creating the ServerMgr singleton, call the function getServerMgr().getFullData().
The function getFullData() is an async function that should await the function requestFetchData() to receive the data from the axios request before returning.
The problem is that getFullData() doesn’t await and go ahead without receiveing the request response so the variable appointmentsResults in the useEffect is undefined.
Using the debugger I confirmed that the axios request is correct because it receives the correct data in the .then but after getFullData() went on.
Can you help me?
Here the code:
ServerMgr
serverMgr.requestFetchData = async (service, args) => {
let data = args
?
JSON.stringify({
"service": service,
...args
})
:
JSON.stringify({
"service": service
})
let config = {
method: 'post',
maxBodyLength: Infinity,
url: my_php_script_url,
headers: {
'Content-Type': 'application/json'
},
data : data
};
axios.request(config)
.then((response) => {
return response.data;
})
.catch((error) => {
console.log("ERROR requestFetchData: " + error);
});
}
serverMgr.getFullData = async (cb) => {
let result = await serverMgr.requestFetchData("getAll")
if(cb) {
console.log("getFullData: " + result)
cb(result)
}
else {
console.log("getFullData: " + result)
return result
}
}
App.js
useEffect(() => {
initSingleton() //this load the singleton
.then(async () => {
let appointmentsResults = await getServerMgr().getFullData()
let appointmentsListClean = removeEmptyAppointments(appointmentsResults)
})
}, [])
const removeEmptyAppointments = (appoArray) => {
return appoArray.filter((item) => (item.appointment_id ? true : false))
}
2
Answers
Can you try
await
axios in therequestFetchData
? You useasync
function but you didn’t put anyawait
, maybe this is a problem ?The method
requestFetchData()
is not returning anything, so it returns a Promise with resultundefined
. You have to return theaxios
response.The code actually returns the
axios
Promise and, since you are not awaiting for anything in you method,requestFetchData()
could be a "sync" function.You could also wait for the
axios
response by doingreturn await axios.request(config)
, but it is not necessary.