I know there are already a couple of questions similar to this, but none of the solutions provided are working for me. I am dispatching an action in my React Native component, but when I try to access the state afterwards with useSelector, it is still just the previous state, not the updated one.
My component:
const userSettings = useSelector((state: any) => state.user.settings);
const loadUserSettings = async () => {
await dispatch(userActions.fetchUserSettings());
}
const checkUserEnabled = async () => {
await loadUserSettings();
// The old state shows here rather than the updated one
console.log(userSettings.enabled)
}
and this is my reducer:
const initialState = {
settings = UserSettings,
};
export default (state = initialState, action) => {
switch (action.type) {
case SET_USER_SETTINGS:
return {
...state,
settings: action.settings,
};
default:
return state;
}
};
userSettings is a stale closure, as Nicolas suggested you cannot dispatch an action and expect the state value to have changed immediately because a new state is created after every action and your current function is still using the old value of the state. When the component re renders it will be re rendered with the new state value.