Reputation: 318
Or in other words, how do i know when a action that's dispatched is complete?
I have a webapp where I'd update the redux store through dispatches on user input. If i push the redux store's state to the server right after dispatching, the server does not have the most updated info. I need to wait for the action to complete prior to pushing to server, hence the question.
EDIT Based on markerikson's answer I solved it. I thought dispatch was called asynchronously but the execution of the group of dispatched actions happened synchronously. That's wrong and mark's right. My issue was the the update server call was made in a component and it pushes to server a prop that needed to be updated by redux-store. That updating of the prop didn't happen fast enough.
Upvotes: 0
Views: 4742
Reputation: 775
A little late to the question, but for the people who got here based on the question title - take a look into:
store.subscribe()
store.getState()
where 'store' is a reference to your redux store.
store.subscribe(() => {
const newState = store.getState();
// check out your updated state
});
the code above would run anytime there is an update to the redux state
Upvotes: 4
Reputation: 67459
Dispatching is entirely synchronous, unless altered by a middleware. So, as soon as the call to dispatch()
returns, the store state has been updated and all subscribers have been notified.
If you need to wait for some async behavior to complete, you can write a thunk that returns a promise, and chain off that when you dispatch:
function someThunkReturningAPromise() {
return (dispatch) => {
const promise = myAjaxLib.fetchData().then(response => {
dispatch(loadData(response.data));
});
return promise;
}
}
dispatch(someThunkReturningAPromise()).then( () => { });
Upvotes: 0