0

I have the following state in React:

const [counter, setCounter] = useState({foo: 1, bar: 1});

and I have data like

const data = [{who: "foo", otherVal: "bla"}, {who: "bar", otherVal: "bla"}];

If I remove an object from the data array, I want to decrease the counter by 1 related to the who value of the deleted object.

If {who: "foo", otherVal: "bla"} gets removed, I want to decrease the foo key of the counter because who === "foo". But In my app I don't know that foo is foo or bar is bar. I must use counter[data.who] somehow to update my state.

John Doener
  • 119
  • 10
  • 3
    `setCounter(counter => ({...counter, [entry.who]: counter[entry.who] - 1 }));` where `entry` is the entry being removed, see the linked question's answers for details. (Be sure to use the callback version of `setCounter` as shown, so you don't accidentally use stale state.) – T.J. Crowder Dec 14 '21 at 12:56
  • The linked answer do not really help as I already know theses fundamentals. But your code helps and works. But to understand and read more about the details - is the `xx => ()` in the setter already the callback version? New to me to see an arrow there . – John Doener Dec 14 '21 at 13:44
  • Yes, that's an arrow function being passed to the state setter, so React will call it with the up-to-date state value. Happy coding! :-) – T.J. Crowder Dec 14 '21 at 13:49
  • When I google `callback version of usestate in react" I don't find any useful information. What is the more common term for that? – John Doener Dec 14 '21 at 14:10
  • 1
    The documentation seems to like the term [functional updates](https://reactjs.org/docs/hooks-reference.html#functional-updates). I'd probably have looked for "callback version of the state setter" but no idea if that would have been more successful. :-) – T.J. Crowder Dec 14 '21 at 14:15
  • Great! Thank you – John Doener Dec 14 '21 at 14:23

0 Answers0