I have a useSelector that would return me the value stored in global state, I also have a async action by using react redux thunk which inside it would change the state value, however, when I call my thunk function and after it finishes, the useSelector value seems not update immediately, it would have a little delay...How could I fetch the latest value from state after executing the thunk function?
// thunk
function savePageData() {
return async(dispatch, getState) => {
await fetch(...).then(res => dispatch(LOAD_DATA, res));
dispatch(somethingelse);
}
}
// main
const myPage = () => {
const user = useSelector(state => return state.user);
const dispatch = useDispatch();
const onClick = async() => {
await dispatch(savePageData());
if (user.active). // here the user after above dispatch is still the old state
{ ... }
}
}
it would work this way
const onClick = async() => {
return (_dispatch, getState) => {
await dispatch(savePageData());
if (getState().user.active). // now user is latest, but is this a correct way and why?
{ ... }
}
}
or this way
const onClick = async() => {
await dispatch(savePageData()).then(
if (user.active). // now user is latest, but is this a correct way and why?
{ ... }
);
}