0.1.1 • Published 4 years ago
immer-path
Licence
MIT
Version
0.1.1
Deps
0
Size
20 kB
Vulns
0
Weekly
0
immer-path
Why
Manipulate JavaScript Object with immer is very easy, but it's hard to manipulate a deep-nested Object.
For example, a <Component /> may handle a state object in the tree.
root
/ \
/ \
2 \
/ \ 3
4 5 / \
9 \
obj <--- `<Component />` render and update this
/ \
6 7
The problem is:
- How to update
objinroot? - How to get next state of
obj?
If <Component /> hold the obj object, we can find it in root tree and update it, but can not get next obj in next root.
So the solution is give every object a $path, <Component /> hold $path of obj, and update & get next value with $path.
Usage
import {
initPath,
producePath,
findByPath,
} from 'immer-path';
const target = {
hey: {
yes: 'hello',
},
};
// init
const targetPath = initPath(target);
// get path, <Component /> hold this
const nodePath = targetPath.hey.$path;
const nextData = producePath(targetPath, (draft) => {
// find obj with path
const node = findByPath(draft, nodePath) as any;
// update it
node.yes = 'yes';
});