immerjs / immer

Create the next immutable state by mutating the current one
https://immerjs.github.io/immer/
MIT License
27.65k stars 848 forks source link

how to modify data with unknown path #1133

Closed millievn closed 2 months ago

millievn commented 3 months ago

i have some data like this:

type Node = {
children: Node[]
id: string
name: string
}

type Tree = {
   tree: Node[]
   id: string
   name: string
}

how to modify node data with unknown and deep path?

mweststrate commented 3 months ago

Same as you would do it without Immer? What did you try / doesn't work?

millievn commented 3 months ago
// first create immer data
let schema = produce(
  {
    "children": [
      {
        "id": "1-1",
        "name": "none",
        "children": [
          {
            "id": "1-1-1",
            "name": "none",
            "children": [
              {
                "id": "1-1-1-1",
                "name": "none",
                "children": []
              },
              {
                "id": "1-1-1-3",
                "name": "none",
                "children": []
              }
            ]
          }
        ]
      },
      {
        "id": "1-1",
        "name": "none",
        "children": []
      }
    ],
    "id": "1",
    "name": "none"
  }, () => {
    // do something
  })

// then i loop schema to render
<DataComponent 'data-is-[1-1]' >
  <DataComponent 'data-is-[1-1-1]' />
</DataComponent>

// so for 1-1-1, i only have [schema] and [its children] and [its parent]
// i waht to add child 1-1-1-2
schema = produce(schema, (draft)=>{
  // there is only draft and data111 is the origin immer data
  // how to find data111 path to modify it?
  data111.children.splice(1,0,data1112)
})

how to find data111 path to modify it?

mweststrate commented 2 months ago

That should work with immer not different than without immer, so this is more of a general "how do I do X in JavaScript", for which stackoverflow is the proper resource.