Reputation: 163
when my props.postToAllData
and props.postToUserData
methods are called, it takes a while for the fetch method to make its course. Thus, I am being pushed to another webpage and the new information doesn't show since Im pushing to a new page quicker than my post method. I cant use .then
method since this isn't a promise. What can i do to push to after the post method finishes?
const onSubmit = (event) => {
event.preventDefault();
if (ingredientsArray.length !== 0 && instructionsArray.length !== 0) {
props.postToAllData(
{
...recipe,
ingredients: ingredientsArray,
instructions: instructionsArray,
img: isSelectedFile,
author: user.username,
},
),
props.postToUserData(
{
...recipe,
ingredients: ingredientsArray,
instructions: instructionsArray,
img: isSelectedFile,
author: user.username,
},
),
resetForm();
history.push('/dashboard/global');
} else setErrorForm('Please fill in all fields');
};
Upvotes: 0
Views: 198
Reputation: 2942
You can use a middleware for redux called thunk. Thunk allows you to write async actions, which you can't with regular redux.
It'll work like this:
Declare an async action with your api call
const myAsyncAtion = () => {
return async () => {
const response = await apiCall();
return response;
}
}
And just dispatch it in your code like any other action. Now it returns a promise, which you can chain with .then
or await
. Cheers!
const save = async () => {
await props.myAsyncAction();
console.log('hooray')
// or
props.myAsyncAction().then(() => console.log('hooray'))
}
Upvotes: 1