Blog>
Snippets

Handling Conditional Updates in createReducer

Provide an example of using Redux Toolkit’s createReducer to handle conditional updates within a nested state based on action payload values.
import { createReducer } from '@reduxjs/toolkit';

const initialState = {
  users: {
    '1': { name: 'Alice', isAdmin: false },
    '2': { name: 'Bob', isAdmin: true }
  }
};

const usersReducer = createReducer(initialState, {
  TOGGLE_ADMIN: (state, action) => {
    const { userId, isAdmin } = action.payload;
    // Check if the user exists and only then update
    if (state.users[userId]) {
      // Update the user's 'isAdmin' status conditionally based on action payload
      state.users[userId].isAdmin = isAdmin;
    }
  }
});

export default usersReducer;
Defines a usersReducer where the 'TOGGLE_ADMIN' action type conditionally updates the 'isAdmin' property of a user object in a nested state. It uses createReducer from Redux Toolkit, which allows for directly mutating the draft state in an immer-powered way to produce the new immutable state.