Search code examples
reduxredux-toolkit

How to call another action from inside a redux toolkit action


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?


Solution

  • Yes, it is a common practice to dispatch multiple actions.

    • Option 1. Dispatch actions directly to the event handler.
    const handler = () => {
      dispatch(reset());
      dispatch(generateCard(2))
    }
    
    • Option 2. Create a thunk to compose related actions (need redux-thunk middleware)
    const resetAndGenerateCard = (cardNumber) => {
      return (dispatch) => {
        dispatch(reset());
        dispatch(generateCard(cardNumber))
      }
    };
    
    const handler = () => dispatch(resetAndGenerateCard(cardNumber))
    
    • Option 3. Create a new special action combine these two action types, and handle it in a special reducer. (The "special" is not really special, it just needs you to think of an action type to represent the meaning of this action. The 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?