Skip to content Skip to sidebar Skip to footer

How To Get Data Returned From Fetch() Promise?

I am having trouble wrapping my head around returning json data from a fetch() call in one function, and storing that result in a variable inside of another function. Here is where

Solution 1:

always return the promises too if you want it to work: - checkUserHosting should return a promise - in your case it return a promise which return the result data.

functioncheckUserHosting(hostEmail, callback) {
    returnfetch('http://localhost:3001/activities/' + hostEmail)
        .then((response) => { 
            return response.json().then((data) => {
                console.log(data);
                return data;
            }).catch((err) => {
                console.log(err);
            }) 
        });
}

and capture it inside .then() in your main code:

functiongetActivity() {
    let jsonData;
    activitiesActions.checkUserHosting(theEmail).then((data) => {
       jsonData = data;
    }        
}

EDIT:

Or even better, use the new syntax as @Senthil Balaji suggested:

const checkUserHosting = async (hostEmail, callback) => {
 let hostEmailData  = awaitfetch(`http://localhost:3001/activities/${hostEmail}`)
 //use string literalslet hostEmailJson = await hostEmailData.json();
 return hostEmailJson;
}

const getActivity = async () => {
 let jsonData = await activitiesActions.checkUserHosting(theEmail);
  //now you can directly use jsonData
}

Solution 2:

You're partially right. It's because you're trying to get the result of this asynchronous call in a synchronous fashion. The only way to do this is the same way you deal with any other promise. Via a .then callback. So for your snippet:

functiongetActivity() {
    return activitiesActions.checkUserHosting(theEmail).then((jsonData) => {
        // Do things with jsonData
    })
}

Any function that depends on an asynchronous operation must itself become asynchronous. So there's no escaping the use of .then for anything that requires the use of the checkUserHosting function.

Solution 3:

You can make use of new ES6 and Es7 syntax and what others have written is also correct, but this can be more readable and clean,

you are trying to get aysnc value synchronously, here jsonData will be undefined because, you move to next line of execution before async function(checkUserHosting) is finish executing, this can be written as follows

const getActivity = async () => {
 let jsonData = await activitiesActions.checkUserHosting(theEmail);
  //now you can directly use jsonData
}

and you can write checkUserHosting in a different using new syntax like this

const checkUserHosting = async (hostEmail, callback) => {
 let hostEmailData  = awaitfetch(`http://localhost:3001/activities/${hostEmail}`)
 //use string literalslet hostEmailJson = await hostEmailData.json();
 return hostEmailJson;
}

Post a Comment for "How To Get Data Returned From Fetch() Promise?"