I am trying to build a React project where I have a component that fetches data from a remote server and plots it.
async function fetchRemoteData(name) {
let dataItem = null;
if (name) {
await fetch("/endpoint/" + name)
.then((res) => res.json())
.then((payload) => {
console.log("payload = " + JSON.stringify(payload));
dataItem = payload;
});
} else {
console.log("Error: No data for " + name);
}
return dataItem;
}
var RenderPlot = ({ match }) => {
let remoteObject = fetchRemoteData(match.params.data);
console.log("remoteObject = " + JSON.stringify(remoteObject));
// .... rendering code
// .... and other irrelevant stuffs to this question
}
If I run this code, on the console, I'm seeing the remoteObject is empty, but the payload inside the function fetchRemoteData() is not.
remoteObject = {}
payload = {"data":"some value"}
Now, let's say I have data stored in the browser (which is obviously I'm not supposed to do, but anyway) and if I fetch it using a generic function call, I'm not having problem.
function fetchLocalData(name) {
// read the data from a local js object
// and return it
}
var RenderPlot = ({ match }) => {
let remoteObject = fetchRemoteData(match.params.data);
console.log("remoteObject = " + JSON.stringify(remoteObject));
let localObject = fetchLocalData(match.params.data);
console.log("localObject = " + JSON.stringify(lovalObject.m))
// .... rendering code
// .... and other irrelevant stuffs to this question
}
and the output --
localObject = 4
remoteObject = {}
payload = {"data":"some value"}
So, what's happening is the code gets the localData from fetchLocalData(), then calls fetchRemoteData() but it doesn't wait if the data is received or not. And then, keeps doing whatever in the rest of the code.
What I want is, the code should wait until the remoteData is received and then proceed to the next steps.
How do I do that?
JSON.stringifyand you'll see thatremoteObjectis not an empty object but a promise