How to use the applyPatches function from immer

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

immer.applyPatches is a function in the Immer library that applies a set of patches to a given state and returns a new state.

78
79
80
81
82
83
84
85
86
87
        return;
    }

    for (let p of patch.result) p.path = p.path.split('/').filter(e => e !== '');

    setData({ accounts: applyPatches(subsData.accounts, patch.result) });
    processAccounts();
});

ec.connect();
fork icon11
star icon34
watch icon0

74
75
76
77
78
79
80
81
82
83
}

for (let p of patch) p.path = p.path.split('/').filter(e => e !== '');

let orig = getter();
let updated = applyPatches(orig, patch);

if (orig !== updated) {
    setter(updated);
    if (this.opts.onUpdate) this.opts.onUpdate();
fork icon3
star icon6
watch icon0

+ 2 other calls in file

How does immer.applyPatches work?

immer.applyPatches is a function in the Immer library that applies a set of patches to a given state and returns a new state. The function takes two arguments: the first argument is the current state object that you want to modify, and the second argument is an array of patches that you want to apply to the state object. Each patch in the array is an object with several properties that describe the change that needs to be made to the state object. The immer.applyPatches function applies each patch in turn to the state object, producing a new state object that reflects the changes described by the patches. Internally, immer.applyPatches uses the same "copy-on-write" mechanism as the rest of the Immer library. When a patch is applied, Immer creates a new copy of the state object and modifies that copy instead of modifying the original object. This allows Immer to track changes to the state object and undo them if necessary, without modifying the original object. immer.applyPatches is useful in situations where you need to make multiple changes to a state object in a controlled and reversible manner, such as when working with complex state in a Redux store.

1
2
3
4
5
6
7
8
9
10
11
12
test("prototype pollution in immer", () => {
  expect({}.polluted).toBe(undefined);


  const { applyPatches, enablePatches } = require("immer");
  enablePatches();
  applyPatches({}, [
    { op: "add", path: ["__proto__", "polluted"], value: "yes" },
  ]);


  expect({}.polluted).toBe("yes");
fork icon1
star icon11
watch icon0

+ 8 other calls in file

2
3
4
5
6
7
8
9
10
enablePatches();
applyPatches({}, [
  { op: "add", path: ["__proto__", "polluted"], value: "yes" },
]);


// applyPatches({}, [
//   { op: "replace", path: ["__proto__", "polluted"], value: "yes" },
// ]);
fork icon1
star icon2
watch icon0

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
const { applyPatches } = require("immer");

// Define the original state object
const state = {
  name: "John",
  age: 30,
  address: {
    street: "123 Main St",
    city: "Anytown",
    state: "CA",
  },
};

// Define a set of patches to apply to the state object
const patches = [
  { op: "replace", path: "/name", value: "Jane" },
  { op: "add", path: "/phone", value: "555-1234" },
  { op: "replace", path: "/address/city", value: "Newtown" },
];

// Apply the patches to the state object
const newState = applyPatches(state, patches);

console.log(newState);

In this example, we start by defining an original state object that contains a name, age, and address. We then define an array of patches that describe changes we want to make to the state object. The first patch replaces the name property with a new value, the second patch adds a new phone property to the state object, and the third patch replaces the city property of the address object with a new value. We then use immer.applyPatches to apply the patches to the original state object and produce a new state object that reflects the changes described by the patches. Finally, we output the new state object to the console using console.log. The output of this example will be a new state object that is identical to the original state object, except that the name property has been changed to "Jane", a new phone property has been added, and the city property of the address object has been changed to "Newtown".

556
557
558
559
560
561
562
563
564

handleUndo = () => {
  if (this.canUndo) {
    let currentVersion = this.currentVersion[this.state.currentPageId];

    const appDefinition = applyPatches(
      this.state.appDefinition,
      this.currentVersionChanges[this.state.currentPageId][currentVersion - 1].undo
    );
fork icon0
star icon1
watch icon1

+ 19 other calls in file

52
53
54
55
56
57
58
59
60
61

  eulerClient.unsubscribe(id); // don't unsubscribe if using immer

  // if using immer:
  //for (let p of patch.result) p.path = p.path.split("/").filter(e => e !== "")
  //result = applyPatches(result, patch.result)

  console.log(patch.result[0].value.epoch);
  console.log(patch.result[0].value.tokens);
}
fork icon0
star icon0
watch icon0

+ 6 other calls in file

59
60
61
62
63
64
65
66
67
68
for (let i = 1; i < patches.length; i++) {
  const patch = JSON.parse(patches[i])

  switch (patch.action) {
    case 'modify':
      jsonObj = applyPatches(jsonObj, patch.payload)
      break
    default:
      throw new Error('Unknown operation')
  }
fork icon0
star icon0
watch icon0

27
28
29
30
31
32
33
34
35
36
37
        console.log(`ERROR: ${err}`);
        return;
    }


    for (let p of patch.result) p.path = p.path.split('/').filter(e => e !== '');
    logs = applyPatches(logs, patch.result);


    console.log(logs);
});
fork icon0
star icon0
watch icon0