Blog>
Snippets

Mapping Object Method to Declare ExtraReducers

Demonstrate using a mapping object to declare extraReducers within the createSlice utility, responding to actions from a different slice.
import { createSlice } from '@reduxjs/toolkit';
import { otherSliceActions } from './otherSlice';

// Define the initial state for the current slice
const initialState = {
    // some state properties
};

const currentSlice = createSlice({
    name: 'current',
    initialState,
    reducers: {
        // Reducer logic for actions defined in the current slice
    },
    extraReducers: {
        // Mapping an action type from 'otherSlice' to a reducer of the current slice
        [otherSliceActions.someAction.type]: (state, action) => {
            // Reducer logic handling 'someAction' from 'otherSlice'
        }
    }
});

export const currentSliceActions = currentSlice.actions;
export default currentSlice.reducer;
This code creates a slice using createSlice from Redux Toolkit and defines extraReducers using an object mapping. It maps an action type from 'otherSlice' to a reducer in the current slice. When 'someAction' is dispatched from 'otherSlice', the corresponding reducer logic in the 'extraReducers' object will be executed, allowing this slice to respond to an action defined elsewhere.