React setState to array element

Viewed 57

I want to update list with React.

List I have:

export const arrList = [
  { title: '', elements: []  },
  { title: 'a', elements: ['aaa',  ]  },
  { title: 'b', elements: ['bbb',  ]  },
];

const [poreikiai, setPoreikiai] = useState(arrList);

And now, I want to append to first array element: elements { title: '', elements: [] }

I something like this:

{ title: '', elements: ["firstElement"] }

how can I do it?

I understant that I need to use setPoreikiai but I cant figure out sintax;

Something like:

    setPoreikiai(prevState => { 
      return {...prevState, ...newValue};
    });```
1 Answers

Deeply clone your way into the data structure and add the new item at the end:

setPoreikiai(prevState => {
  const prevClone = [...prevState];
  
  prevClone[0] = {
    ...prevClone[0],
    elements: [...prevClone[0].elements, "secondItem"]
  };
  
  return prevClone;
});

It's important that you create copies all the way down to the desired level of state so that you do not accidently mutate any values by reference. Any directly mutated data can become out of sync with other effects and memoised components which might accept them as dependencies.

Related