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...
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
}
}