'Selector returns previous value
I have a redux-toolkit slice with a 'loading' state value that is initially set to idle.
When dispatching a createAsyncThunk action, the loading state value is updated to pending, and I can observe that the state is updated correctly from the Redux dev tools.
The dispatch is called inside a useEffect with the value from the loading selector in the dependency array.
I test that the value is equal to 'idle' before dispatching the action. But somehow, the action is dispatched at least twice (many more times in my code). Why ?
It looks like the selector is not picking up the state change.
Here is a minimal reproducible example sandbox: https://codesandbox.io/s/hungry-sammet-0smieb
Solution 1:[1]
This is the behavior of the StrictMode component.
useEffect(() => {
if (loading === "idle") {
console.count(loading);
dispatch(getSomething());
}
}, [loading, dispatch]);
With the StrictMode component, the logs:
idle: 1
idle: 2
Without the StrictMode component, the logs:
idle: 1
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | slideshowp2 |
