There's no way to know when the state is updated when using dispatch
j
jason
In React, when I call setState, it has a callback to notify me the state has been setted. But when I use Redux, I use dispatch to change the state, but how can I know if the state has been updated.
For example:
dispatch({type: 'setCount', {count: 1}});
dispatch({type: 'add', {addedCount: this.state.count + 1}})
the second line depends on the first line, but we all know setState is not a synchronous operation, how can I handle this issue in Redux
Nat Kuhn
I agree! 1. This has come up on SO a few times. (https://stackoverflow.com/questions/37684631/react-reduxget-the-latest-props-value-from-state-after-updating-props-with-disp, https://stackoverflow.com/questions/39524855/how-to-trigger-off-callback-after-updating-state-in-redux).
- It seems like the one feature of react state management that is not included in redux.
- Sometimes you want to be able to trigger a side effect after the store is updated. My use case involves redux and react-router. If the URL location changes so that it is out of sync with the store, I <Prompt> to see if the the user wants to change. If so, I need to update the store, and then do history.push AFTER the store is updated. There are various workarounds. Mine is (a) I moved the history.push to a useEffect method, which put the code in an isolated spot where it doesn't really belong, logically; (b) I could add a store listener, but would have to set up a way to filter out all the other events; (c) perhaps some redux router package would solve this but I would have to research it, learn it, and add another dependency.
Here is my proposal: add another argument to dispatch: dispatch(action,callback). After the reducer spits out the new value of state and the store is updated, redux would call callback(store, dispatch, action). store would give access to state; dispatch would allow chaining of further actions, and action would presumably be the final action that triggered the reducer.
The major problem is that this would break all existing middleware AFAIK, but it would be relatively easy to fix any individual middleware.
I could try to do a PR if this is actually of interest.