In-store I have an array called visited:[]. In a function called changeInfo first I need to clear the array and then add an item to the array.
const changeInfo = (value) => {
dispatch(clearVisited());
console.log("before visited", visited);
dispatch(addToVisited(value));
console.log("after visited", visited);
};
Some can argue that I can have an action type clearAndInsert and reducer like this
case CLEAR_AND_INSERT:
return {
visited: [action.payload],
};
But this is not wanted I want. I want to dispatch clearVisited and wait until after it clears the array and after that dispatch addToVisited.Want I am getting for the console logs for changeInfo is strange.
HOW CAN I CALL TWO ACTIONS SYNCHRONOUSLY IN REACT?
Reducers are synchronous. As soon as dispatch(clearVisited()); finishes, the store has been updated. However, rerendering a react component is not synchronous, and the local variable visited is not going to be changed by dispatching an action. So you're logging out an old local variable, and that's misleading you into thinking the redux store has not been updated.
If you'd like to verify that the store has been updated, even though the component has not yet rerendered, you could get the latest state directly from the store
const changeInfo = (value) => {
dispatch(clearVisited());
console.log("before visited", store.getState());
dispatch(addToVisited(value));
console.log("after visited", store.getState());
};
Alternatively, if you're fine with waiting until the component has rerendered, you can put your log statement in the body of the component, not in changeInfo.
console.log('rendering with', visited);
const changeInfo = (value) => {
dispatch(clearVisited());
dispatch(addToVisited(value));
};
The values will only update in their next render(), so you cannot read values inside the same function. add console in a useEffect.
below method will only print old values, not updated one
const changeInfo = (value) => {
dispatch(clearVisited());
console.log("before visited", visited); //this will only console previous value, because it is not yet updated
dispatch(addToVisited(value));
console.log("after visited", visited); //this will only console same previous value, because it is not yet updated
};
you can call actions it will update reducer one after another
you can check the update in a useEffect
useEffect(()=> {
console.log(visited)
},[visited])