Extra Reducers
extraReducers in RTK 
extraReducers in RTK extraReducers allows createSlice to respond to other action types besides it's own action types. 
// Importing the createSlice function
const { createSlice } = require("@reduxjs/toolkit");
const { counterActions } = require("../counter/counterSlice");
// Initial state for the counter
const initialState = {
  count: 0,
};
// Creating a counter slice using the createSlice function
const keeperSlice = createSlice({
  // Name of the slice
  name: "keeper",
  // Initial state for the slice
  initialState: initialState,
  // Reducers define how the state should be updated based on dispatched actions
  reducers: {
    // Reducer for incrementing the count
    increment: (state, action) => {
      state.count += 1; // Incrementing the count property in the state
    },
    // Reducer for decrementing the count
    decrement: (state, action) => {
      state.count -= 1; // Decrementing the count property in the state
    },
  },
  // Extra reducers are used to handle actions dispatched from other slices
  // Here, we are adding a case for the decrement action from the counterActions slice.
  extraReducers: (builder) => {
    builder.addCase(counterActions.decrement, (state, action) => {
      state.count -= 1;
    });
  },
});
// Exporting the reducer function generated by createSlice
module.exports = keeperSlice.reducer;
// Exporting the actions generated by createSlice
module.exports.keeperActions = keeperSlice.actions;
Last updated
Was this helpful?