Search code examples
javascriptreactjsecmascript-6ecmascript-5

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


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.


Solution

  • Try this

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