0

I'm working with a custom Library in React, where you can add emojis, And I'm trying to make a counter variable to the object, which increases each time a user clicks on it.

The point is to make it into an array, of several emojis, but so far, I'm trying to make it work with only one.

So I have a condition rather the emoji should be shown or not

{
  this.state.showEmoji &&
    <div className="emoji">
      <Emoji 
        onClick={this.increment}
        emoji={{ id: this.state.emoji.id, skin: 1, }}
        size={25}
      />
      <p>{this.state.emoji.count}</p>
    </div>
}

Inside I render my Emoji along with the counter, which determinates how many times the emoji has been rendered/clicked

I'm not sure if I should make an anonymous function or make a handler, I tried out with the handler

I have made a custom emoji object in my state (which will eventually be an array of emoji objects)

emoji: {
  id: '',
  count: 0,
}

Along with my increment handler method:

increment = (emoji) =>{
  console.log(emoji.id);
  console.log(this.state.emoji.id);
  this.setState({
   count: this.state.emoji[emoji.id].count++
  });
}

I successfully console log the emoji objects state id and then passed in emoji object, and they match.

But when I try to mutate the state I get this error:

TypeError: Cannot read property 'count' of undefined

Why can't I access the object with the id in this case?

2
  • What do you think is going to happen with this.state.emoji[emoji.id]? Commented Dec 6, 2018 at 8:41
  • I was wondering if it would access the object, but since there is only one, i don't think it will be necessary Commented Dec 6, 2018 at 8:43

2 Answers 2

2
increment = (emoji) =>{
 const { emoji } = this.state; // isn't that more readable?
 const _emoji = {
   ...emoji,
   count: emoji.count + 1
 } //this will create a copy of your emoji object.
   // use +1 instead of ++ to make sure you are keeping the original count value as it is, 'PURE PROGRAMMING'
 this.setState({ emoji: _emoji });
}
Sign up to request clarification or add additional context in comments.

Comments

0

Please take a look at this sandbox code, it may help with managing the array of emojis as well.

Comments

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.