0

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.

1
  • setCounter accepts an array and replaces counter (all the counters!). NIT: you should call the state object counters (in plural). Commented Sep 29, 2022 at 19:50

1 Answer 1

1

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] }
    ]
  );
};
Sign up to request clarification or add additional context in comments.

1 Comment

Great answer mate, I literally just finished writing the same thing out but you've beaten me to the punch XD. Had to tweak some of my code around but this now works exactly like how I want it to.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.