Home > Mobile >  How to update nested object having array with useState in Reactjs?
How to update nested object having array with useState in Reactjs?

Time:10-11

Hello Developers how are you?

I am trying to update nested values, but all are failing.

const [ControlGaps, setControlGaps] = useState([
    {
      id: 1,
      name: "Pizza 1",
      status: 1,
      applicable: true,
      questions: [
        {
          id: 1,
          question:
            "how are you?",
          answer: null,
          evidence: null,
          treatment: null,
          type: "Implemented",
        {
          id: 2,
          evidence: null,
          treatment: null,
          type: "Implemented",
          question:
            "how old are you?",
          answer: null,
         }
      ],
    },
    {
      id: 2,
      name: "Pizza 2",
      status: 1,
      applicable: true,
      questions: [
        {
          id: 1,
          type: "Implemented",

          question:
            "How are you 2?",
          answer: null,
          evidence: null,
          treatment: null,
         
        {
          id: 2,
          answer: null,
          evidence: null,
          treatment: null,
          type: "Implemented",
          question:
            "How old are you?",
        },
      ],
    }])

I tried to use onChange this

    setControlGaps([...ControlGaps, [ControlGaps[index]].applicable]:checked]);

or

    setControlGaps({
      ...ControlGaps,
      [ControlGaps[index].applicable]: checked,
    });

But it's all wrong.

The question is how to update values in nested field like updating fields in object inside array of objects for example.

CodePudding user response:

Can be done using some slice() and spread. But you should look at immutability helpers for such nested stuff.

setControlGaps([setControlGaps.slice(0,index),
{ ...ControlGaps[index],
 applicable : checked
}
,setControlGaps.slice(index 1)]);

CodePudding user response:

Try this

setControlGaps(prevState => {
    const newState = prevState.map((item, itemIndex) => {
        if (itemIndex === index) {
            item.applicable = false;
            return item;
        }
        return item;
    });
    return newState;
});
  • Related