Home > database >  How do I update a specific key in an array of keys using React
How do I update a specific key in an array of keys using React

Time:09-30

I've got a counter array, containing 3 objects.

const [counter, setCounter] = useState([
  { id: 0, count: [] },
  { id: 1, count: [] },
  { id: 2, count: [] }
])

Theres then 3 buttons that when pressed call the following function.

const update = (i, text) => {
  setCounter(currCount =>
    currCount.id === i
      ? { id: i, count: [...counter[i].count, text] }
      : currCount
  );
};

The buttons pass "i" which is 0,1,2 corresponding to the 3 object ids and "text" which is the error text. The function should update the specific object from the array adding the new error text to that id's count array. I cant seem to get this to work though, it keeps returning undefined.

Any help is appreiciated.

CodePudding user response:

The useState dispatch function (setCounter in your case) replaces the whole state with the value it is provided with.

In your example, you need to recreate the whole array like so:

const update = (i, text) => {
  setCounter(currCounter =>
    [
      ...currCounter.filter(count => count.id !== i), // the old counter state without the one we want to change
      { id: i, count: [...currCounter[i].count, text] }
    ]
  );
};
  • Related