I encountered an issue while using Redux in my React component. Initially, I was trying to dispatch an action and then immediately dispatch another one afterwards. Here’s the original code snippet:
const onClickBtn = () => {
dispatch(
addProductStockAndPrices({
productId: itemId,
stockData,
})
);
dispatch(getProductById(itemId));
}
However, this approach didn’t work as expected. Later, I tried a different approach and it resolved the issue:
const onClickBtn = () => {
dispatch(
addProductStockAndPrices({
productId: itemId,
stockData,
})
).finally(() => {
console.log("finished addProductStockAndPrices");
dispatch(getProductById(itemId));
});
}
Can someone explain why the first approach didn’t work while the second one did? I’m using React, Zod, React Hook Form, and Redux Toolkit. Any insights would be appreciated.
2
Answers
The first example dispatched two async actions in parallel. You do not control the order they are to be executed, just the order they are scheduled for execution.
In the second example, the
finally
will only happen after the promise of the first dispatch resolves, hence u unknowingly(?) controlled the order the actions got dispatched.I feel like instead of calling two redux actions back to back once could just add a new action that sets both of those states in the reducer.
addProductAndSetActive