Incrementing count of object inside array

I have a function to make emojis in ReactJS

addEmoji = (emoji) =>{

  //with array function


 let newEmoji = {
    id: emoji.id,
    count: 1
  };
  if(this.state.emojis.filter(emoji =>{
    if(emoji.id === newEmoji.id){
      this.increment(newEmoji);
    }
  }))
  console.log(this.state.emojis)
  this.setState( prevState => ({
    emojis: [...prevState.emojis, newEmoji],
    showEmoji: true
  }))

it accepts a custom emoji object, from the emoji-mart node module

My issue now is that I want to make a check if the object has already been displayed, and increase the count if it has.

I have made this increment, method, where the count for each emoji object is incremented. My issue is that I have to mutate the state, of that one object inside the entire array, which is giving me difficulties

increment = (newEmoji) =>{
 console.log(id);

  let count = newEmoji.count
  count = newEmoji.count+1
  console.log(newEmoji.count)
 this.setState(   

   {emoji: newEmoji} // how do i change the state of that one obejct inside the array
 )
 console.log(this.state.emoji.count)
}

Edit: I have provided the state, to see have the state is being set.

this.state= {
 emojis: []
}

Upvotes: 2

Views: 810

Answers (1)

Lyubomir
Lyubomir

Reputation: 20027

You can recreate the whole array while iterating over it and change the emoji's count where necessary, two birds with one stone. Here is untested version:

// mark if new emoji is already in the array or not
let containsNewEmoji = false;

// recreate emojis array
let newEmojis = this.state.emojis.map(emoji => {
  // if emoji already there, simply increment count
  if (emoji.id === newEmoji.id) {
    containsNewEmoji = true;

    return { 
      ...newEmoji,
      ...emoji,
      count: emoji.count + 1,
    };
  }

  // otherwise return a copy of previos emoji
  return {
    ...emoji
  };
});

// if newEmoji was not in the array previously, add it freshly
if (!containsNewEmoji) {
  newEmojis = [...newEmojis, {...newEmoji, count: 0}];
}

// set new state
this.setState({ emojis: newEmojis });

Upvotes: 1

Related Questions