In thunks, we do not know the current state because maybe some other actions has changed the state during the thunk. So you offered an update function.
But a better solution is offer a getState function...
@xialvjun The update function can _take a function that receives the latest state_. I find this scheme an improvement to ReduxThunk getState.
update(state => ({ count: state.count + 1 }))
And for completeness, when you don't need the latest state to calculate the next state, just pass the new state/slice to update.
update({ count: 1 })
Does that make things clear?
But if the state has been changed during the thunk, then state.count is wrong.
@xialvjun That problem is solved using:
update(state => ({ count: state.count + 1 }))
The state passed to the inner thunk above is always up-to-date.
@xialvjun In other words:
const actions = {
upAsyncNaive(state) { // Hey! state may be out-of-sync here!
return update => update({ count: state.count + 1 })
},
upAsyncSmart(state) { // No problem here!
return update => update(state => ({ count: state.count + 1 }))
}
}
got it. thanks very much.
Glad you figured it out! 馃帀
Most helpful comment
got it. thanks very much.