Blog>
Snippets

Handling Nested State Updates

Provide an example of using createReducer to update a nested state object within a user profile section of the state.
import { createAction, createReducer } from '@reduxjs/toolkit';

// Define an action creator for updating the user's profile
const updateUserProfile = createAction('user/updateProfile');

// Initial state for the user profile
const initialState = {
  profile: {
    name: '',
    email: '',
    details: {
      bio: '',
      location: '',
    }
  }
};

// Create a reducer using the createReducer function from Redux Toolkit
const userProfileReducer = createReducer(initialState, (builder) => {
  builder.addCase(updateUserProfile, (state, action) => {
    // Update the name and email directly
    state.profile.name = action.payload.name;
    state.profile.email = action.payload.email;
    // Nested update for the details object using spread operator
    state.profile.details = {
      ...state.profile.details,
      bio: action.payload.details.bio,
      location: action.payload.details.location,
    };
  });
});

export default userProfileReducer;
This code defines an action creator for updating a user's profile and a reducer to handle the changes. The initial state includes a nested 'details' object. The reducer uses the 'createReducer' function from Redux Toolkit, allowing us to handle actions with an immer draft state. The 'updateUserProfile' action applies updates to both the top-level profile fields (name, email) and nested fields within 'details' (bio, location) safely, using an immutable update pattern.