'Using ImmerJS to update child (by id) within a parent (by id)

How do I update the content of child12 using immerJS

const [fields, setFields] = useState([
    {
        name: "Parent 1",
        id: "parent1",
        children: [
            {id:"child11", content=""},
            {id:"child12", content=""}
        ],
    },
    {
        name: "Parent 2",
        id: "parent2",
        children: [
            {id:"child21", content=""},
            {id:"child22", content=""}
        ],
    },
]);

I have been able to achieve changing the parent name using the following:

    setFields(
        produce((draft) => {
            const field = draft.find((field) => field.id === "parent1");
            field[name] = "new parent1";
        })
    );

How do I go deeper, find within children the child by id and change its content value?



Solution 1:[1]

Turns out it is remarkably simple: just mutate the data.

setFields(
    produce((draft) => {
        const child = draft.find((field) => field.id === "parent1").children.find((child)=>child.id==="child21");
        child[content] = "new value";
    })
);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Eric P