0

I have a chat application in React, I have a checkbox beside text when I click checkbox I take the text message. I just want to store the text in array. When I store the text I use this code:

this.setState(() =>{
     this.state.allMessage.push(message.content.text);
});

But I can store only one, let's say I click checkbox and I send to the array "Hello world". Then I click checkbox "Hello Guys", and only this is stored to array. I just want to add like this:

allMessage: ["Hello World" , "Hello Guys"]
How can add like this.
Now, when I push "Hello Guys" then "Hello world" is deleting automatically.

2
  • Sorry, can't understand exactly what you need, but, you want to remove the last message from array every time a new message is pushed? If so, isn't just clear the array then push? or even, why an array? Commented Jun 17, 2021 at 16:31
  • I just want to add array to string but when i use this push method not work. For example: I have a 3 string "Example1" "example2" "example3" ı did this.state.allMessage.push"Example1"] its okay ı send it. but when i try again this.state.AllMessage.push("Example2") its also okay but "Example1" is deleting how can i store ? ı dont want to deleting first one Commented Jun 17, 2021 at 16:33

2 Answers 2

2

Don't mutate state:

this.setState({
   allMessages: [
     ...this.state.allMessages, 
     message.content.text
   ]
})

This might not solve your exact problem, but it's the first step.

like that how can add like this. When i push "Hello Guys" "Hello world" deleting automatically.

Do you event want an array then if you only want to keep one item in state at a time?

You could do this:

onToggleMessageCheckbox(e) {
  this.setState({
   allMessages: e.target.checked ? [e.target.value] : []
  });
}

If you do want to maintain the state of both checkboxes:

onToggleMessageCheckbox(e) {
  this.setState(state => ({
   ...state, 
   allMessages: e.target.checked ? state.allMessages.concat(e.target.value) : state.allMessages.filter(m => m !== e.target.value)
  });
}
Sign up to request clarification or add additional context in comments.

Comments

0

This will work

this.setState(() =>{
 allMessages:[...this.state.allMessages,message.content.text]
});

It means that you are modifying the state value by keeping all existing value and add your new value.

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.