Home > Net >  useState to update an instance variable of many variables inside an object
useState to update an instance variable of many variables inside an object

Time:04-07

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..

CodePudding user response:

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

  • Related