0.1.1 • Published 2 years ago

immer-path v0.1.1

Weekly downloads
-
License
MIT
Repository
-
Last release
2 years ago

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',
  },
};

// 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';
});