How to get data returned from fetch() promise?

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.

function checkUserHosting(hostEmail, callback) {
    return fetch('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:

function getActivity() {
    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  = await fetch(`http://localhost:3001/activities/${hostEmail}`)
 //use string literals
 let hostEmailJson = await hostEmailData.json();
 return hostEmailJson;
}

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

Leave a Comment