How to use the createDraft function from immer

Find comprehensive JavaScript immer.createDraft code examples handpicked from public code repositorys.

immer.createDraft is a function that creates a draft of a given state, which can then be mutated and produce a new state without changing the original one.

59
60
61
62
63
64
65
66
67
68
  return function () {
    return listeners["delete"](listener);
  };
}
function dispatch(recipeOrPartial) {
  var draft = immer.createDraft(STATE);
  if (typeof recipeOrPartial === 'function') {
    return PromiseResolve(recipeOrPartial(draft)).then(function () {
      return notify(immer.finishDraft(draft));
    });
fork icon0
star icon4
watch icon1

+ 11 other calls in file

How does immer.createDraft work?

immer.createDraft is a function that takes an object and creates a draft copy of that object, allowing changes to be made to the draft without mutating the original object. When you make changes to the draft object, the changes are tracked by Immer, and a new copy of the object with the changes is returned when you call immer.finishDraft(draft). This is useful for managing state in applications where you want to avoid directly mutating the original state.

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import produce, { createDraft } from "immer";

const state = {
  name: "John",
  age: 30,
  address: {
    street: "123 Main St",
    city: "Anytown",
    state: "CA",
    zip: "12345",
  },
};

// create a draft of the state
const draft = createDraft(state);

// make changes to the draft
draft.age = 31;
draft.address.city = "Othertown";

// use `produce` to finalize the changes
const newState = produce(draft, (draft) => {
  draft.name = "Jane";
});

console.log(newState);

In this example, createDraft is used to create a draft of an object state. The draft is then modified to change the age property and the city property of the nested address object. The produce function is then used to finalize the changes by applying the modifications made in the draft and creating a new state object newState.