const scoreSlice = createSlice({
name: 'score',
initialState,
reducers: {
addScore: ({ score }, action) => {
score += action.payload;
},
reset: (state) => {
state.score = 0;
state.grid = initialState.grid;
generateCard(2); // How do we do this?
},
generateCard: (state, action: PayloadAction<number>) => {
},
},
});
I created a scoreSlice
slice
and created 3 actions: addScore
reset
generateCard
.
When I execute the reset
action, I want the generateCard
action to also work. How can I do this?
Yes, it is a common practice to dispatch multiple actions.
const handler = () => {
dispatch(reset());
dispatch(generateCard(2))
}
redux-thunk
middleware)const resetAndGenerateCard = (cardNumber) => {
return (dispatch) => {
dispatch(reset());
dispatch(generateCard(cardNumber))
}
};
const handler = () => dispatch(resetAndGenerateCard(cardNumber))
action1AndAction2
format maybe not good action type)const resetAndGenerateCard = (payload) => ({ type: 'RESET_AND_GENERATE_CARD', payload });
// ...
{
resetAndGenerateCardReducer: (state, action) => {
// reset
state.score = 0;
state.grid = initialState.grid;
// generate card
state.cards = [...state.cards, action.payload];
}
}
// ...
const handler = () => dispatch(resetAndGenerateCard(2))
But sometimes there are trade-offs. Take a look at Should I dispatch multiple actions in a row from one action creator?