Blog>
Snippets

Cross-Slice Action Handling with ExtraReducers

Provide a practical example of using extraReducers to handle an action shared across multiple slices, ensuring that state updates are correctly performed in all affected slices.
import { createAction, createSlice } from '@reduxjs/toolkit';

// An action defined outside the slices
export const logoutUser = createAction('user/logout');

// First slice that needs to respond to the 'user/logout' action
const sliceA = createSlice({
  name: 'sliceA',
  initialState: { data: [] },
  reducers: {},
  extraReducers: (builder) => {
    builder.addCase(logoutUser, (state, action) => {
      // Handle the action in sliceA, e.g., by clearing data
      state.data = [];
    });
  }
});

// Second slice that also needs to respond to the 'user/logout' action
const sliceB = createSlice({
  name: 'sliceB',
  initialState: { profile: null },
  reducers: {},
  extraReducers: (builder) => {
    builder.addCase(logoutUser, (state, action) => {
      // Handle the action in sliceB, for example by resetting profile
      state.profile = null;
    });
  }
});
This example demonstrates how two different slices, 'sliceA' and 'sliceB', can respond to the same action 'user/logout', which is created outside of the slices using createAction. The extraReducers builder.addCase method is used within each slice to update its respective state when that action is dispatched.