In React, state is not be updated instantly, so we can use callback in setState(state, callback)
. But how to do it in Redux?
After calling the this.props.dispatch(updateState(key, value))
, I need to do something with the updated state immediately.
Is there any way I can call a callback with the latest state like what I do in React?
You can use a thunk with a callback
The most important point about React is one-way data flow. In your example that means, that dispatching an action and state change handling should be decoupled.
You shouldn't think like "I did
A
, nowX
becomesY
and I handle it", but "What do I do whenX
becomesY
", without any relation toA
. Store state can be updated from mutiple sources, in addition to your component, Time Travel also can change state and it will not be passed through yourA
dispatch point.Basically that means that you should use
componentWillReceiveProps
as it was proposed by @UtroYou could use
subscribe
listener and it will be called when an action is dispatched. Inside the listener you will get the latest store data.http://redux.js.org/docs/api/Store.html#subscribelistener
component should be updated to receive new props.
there are ways to achieve your goal:
1. componentDidUpdate check if value is changed, then do something..
2. redux-promise ( middleware will dispatch the resolved value of the promise)
then in component
2. redux-thunk
then in component