How to Retrieve Data from Promise Object in React Js

I am trying to get data from an API. But the fetch result is returned as promise object. I want to return the contents from this promise to invoke react action.

let loginData = fetch(loginURL, { method : 'POST', headers : headerParams, 
 body: bodyParams })
  .then((response) => response.json())
  .then(data => {
    return data['retrieve-agent'];
});
console.log('loginData ===>', loginData.agent);
return {
  type: 'GET_AGENT_DETAILS',
  payload: loginData
}

1 Answer

Make use of async-await to get the result without using a promise or else you would need to resolve the promise from the function

async fetchFunction() {

    let loginData = await fetch(loginURL, { method : 'POST', headers : headerParams, 
     body: bodyParams })
      .then((response) => response.json())
      .then(data => {
        return data['retrieve-agent'];
    });
    console.log('loginData ===>', loginData.agent);
    return {
      type: 'GET_AGENT_DETAILS',
      payload: loginData
    }

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

David Miller

David Miller

Executive Financial & Market Analyst

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.

Share this article
Twitter Facebook Pinterest