2

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: []
}

1 Answer 1

1

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 });
Sign up to request clarification or add additional context in comments.

8 Comments

Perfect! but then i would also need to add the logic to add an emoji to the array initially in the same function?`
if (!containsNewEmoji) { newEmojis = [...newEmojis, newEmoji]; } this takes care of it, no?
OK I've edited my answer, we have to also initialize the initial count of emoji with 0: newEmojis = [...newEmojis, {...newEmoji, count: 0}];
it says can't read property 0 of undefined, when I inserted the new code, is it because it does not recognize the newEmoji objects count variable?
I think it's because its initialized to a number to late, when its incremented, it's still undefined
|

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.