-
-
Notifications
You must be signed in to change notification settings - Fork 324
/
Copy pathutils.js
35 lines (31 loc) · 919 Bytes
/
utils.js
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
27
28
29
30
31
32
33
34
35
import React from "react";
import jsonpatch from "fast-json-patch";
export function useJsonPatchCallback(initial) {
const model = React.useRef(initial);
const forceUpdate = useForceUpdate();
const applyPatch = React.useCallback(
(pathPrefix, patch) => {
if (pathPrefix) {
patch = patch.map((op) =>
Object.assign({}, op, { path: pathPrefix + op.path })
);
}
// Always return a newDocument because React checks some attributes of the model
// (e.g. model.attributes.style is checked for identity)
model.current = jsonpatch.applyPatch(
model.current,
patch,
false,
false,
true
).newDocument;
forceUpdate();
},
[model]
);
return [model.current, applyPatch];
}
function useForceUpdate() {
const [, updateState] = React.useState();
return React.useCallback(() => updateState({}), []);
}