Blog>
Snippets

Using patch versions with Immer

Explain how to use Immer's patch feature to record changes made in a reducer and apply them elsewhere.
<div id='app'>Check the console for patch operations.</div>
A simple HTML container where the output will be directed.
/* CSS is not required for the Immer patch functionality. */
No CSS is needed to demonstrate the Immer patch feature.
import produce, { applyPatches } from 'immer';

// Initial state
const initialState = {
  user: {
    name: 'Alice',
    age: 25
  }
};

// Let's assume we want to listen for changes in our state
let patches = [];
let inversePatches = [];

// Our reducer function
const userReducer = produce(
  (draft, action) => {
    switch (action.type) {
      case 'UPDATE_NAME':
        draft.user.name = action.payload;
        break;
      // Add more cases as needed
      default:
        // Handle default case
    }
  },
  // Let's record the patches
  (patchesArg, inversePatchesArg) => {
    patches.push(...patchesArg);
    inversePatches.push(...inversePatchesArg);
  }
);

// Example action
const updateNameAction = {
  type: 'UPDATE_NAME',
  payload: 'Bob'
};

// Dispatch the action to get the new state and record patches
const newState = userReducer(initialState, updateNameAction);

console.log('New State:', newState);
console.log('Patches:', patches);
console.log('Inverse Patches:', inversePatches);

// Now let's say we want to apply these patches to another state
const otherState = {
  user: {
    name: 'Charlie',
    age: 30
  }
};

const updatedOtherState = applyPatches(otherState, patches);
console.log('Updated Other State:', updatedOtherState);
JavaScript code using Immer to create a reducer where changes are recorded using patches. This code also demonstrates how to apply recorded patches to another state object.