Skip to content

Instantly share code, notes, and snippets.

@cbschuld
Created August 3, 2019 21:50
Show Gist options
  • Save cbschuld/e7a69249dbd54665e6f905800cf78638 to your computer and use it in GitHub Desktop.
Save cbschuld/e7a69249dbd54665e6f905800cf78638 to your computer and use it in GitHub Desktop.
Mutations Patterns for Immer in React JS

Object Mutations

import produce from "immer";

const todosObj = {
  id0: { done: true,  body: 'forget immer patterns' },
  id1: { done: false, body: 'remember the immer patterns' }
  id2: { done: false, body: 'finish project' }
};

// add
const addedTodosObj = produce(todosObj, draft => {
  draft['id3'] = { done: false, body: 'remember how to add objects' };
});

// delete
const deletedTodosObj = produce(todosObj, draft => {
  delete draft['id2'];
});

// update
const updatedTodosObj = produce(todosObj, draft => {
  draft['id1'].done = true;
});

Array Mutations

// array mutations
const todosArray = [
  { id: 'id0', done: true,  body: 'forget immer patterns' },
  { id: 'id1', done: false, body: 'remember the immer patterns' },
  { id: 'id2', done: false, body: 'finish project' }
];

// add
const addedTodosArray = produce(todosArray, draft => {
  draft.push({ id: 'id3', done: false, body: 'remeber how to add to an array' });
});

// delete
const deletedTodosArray = produce(todosArray, draft => {
  draft.splice(draft.findIndex(todo => todo.id === 'id2'), 1);
});

// update
const updatedTodosArray = produce(todosArray, draft => {
  draft[draft.findIndex(todo => todo.id === 'id1')].done = true;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment