'useState to update an instance variable of many variables inside an object

const [emoji, setEmoji] = useState({
like: 0,
love: 0,
laugh: 0,
sad: 0,
wow: 0,
angry: 0,

})


const emojiCount = () => {

  isReacted 
  ? 
  setEmoji(emoji => ({...emoji, laugh: emoji.laugh+1}))
  :
  setEmoji(emoji => ({...emoji, laugh: emoji.laugh-1}))
  setIsReacted(!isReacted)

  }
  • isReacted is just a boolean state!

What I am trying to implement is to handle the whole state with the function "emojiCount", I want to know if I am capable of passing "laugh" as a dynamic variable where it can be "love" or "like" etc..



Solution 1:[1]

I think what you want to do is pass the object key dynamically, you can do that like this:

const [emoji, setEmoji] = useState({
  like: 0,
  love: 0,
  laugh: 0,
  sad: 0,
  wow: 0,
  angry: 0,
});


const emojiCount = (emojiIcon) => {
  setEmoji({
    ...emoji,
    [emojiIcon]: emoji[emojiIcon] + 1,
  });
}

So if you call the function like emojiCount("laugh") it will update the laugh key incrementing the laugh value by 1.

Here's a sandbox with dynamic buttons that update the emoji: https://codesandbox.io/s/adoring-benz-2zeyzh?file=/src/App.js

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jean182