I have a reducer function in which I have to make an API call and then return its result as state. But because of the API call being asynchronous the value of state is not updated.
if (action.type==='CREATE_POST') {
const x= async () => {
const res=await fetch("http://localhost:5000/posts", {
method: "post",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(
action.payload
)
})
const data= await res.json()
return data
}
return [...state,x]
}
I have also tried this
if (action.type==='CREATE_POST') {
const x= async () => {
const res=await fetch("http://localhost:5000/posts", {
method: "post",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(
action.payload
)
})
const data= await res.json()
return data
}
return [...state,x().then((data)=>{console.log(data);})]
}