Reputation: 819
I am using the useDispatch() function to return me a dispatch object to fire some actions.
I have a particular scenario in which I want to fire a reject-action that cancels a user's request and after getting back the response from the server (whether it is successful or not) I will decide whether I should fire another action.
My method looks like this:
const reject = () => {
dispatch(method1(data));
dispatch(fetchAll());
}
When.i observe the logs on my developer's console, both method1()
and fetchAll()
both fires off without waiting for the response.
How do I ensure that the method1() returns some value before processing the fetchAll()?
Upvotes: 2
Views: 1738
Reputation: 102467
You need to use redux-thunk middleware. Take look at Composition
Redux Thunk middleware allows you to write action creators that return a function instead of an action. The thunk can be used to delay the dispatch of an action, or to dispatch only if a certain condition is met.
Then you can dispatch the action like this:
const reject = () => {
dispatch(method1(data)).then(res => {
if(res.success) {
dispatch(fetchAll());
}
})
}
Upvotes: 1