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
obj
in root
? - 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',
},
};
const targetPath = initPath(target);
const nodePath = targetPath.hey.$$path;
const nextData = producePath(targetPath, (draft) => {
const node = findByPath(draft, nodePath) as any;
node.yes = 'yes';
});