Hi I have an issue to share with you guys. I got an issue if I wrap the with . You will have your code inside setState run twice. The possible way to fix this is to move the logic outside of setState. I have fix this two setState in App.js.
in componentDidMount -> I moved the msg.reverse() outside setState
componentDidMount() {
this.socket = io(config[process.env.NODE_ENV].endpoint);
// Load the last 10 messages in the window.
this.socket.on('init', (msg) => {
let msgReversed = msg.reverse();
this.setState((state) => ({
chat: [...state.chat, ...msgReversed],
}), this.scrollToBottom);
});
// Update the chat if a new message is broadcasted.
this.socket.on('push', (msg) => {
this.setState((state) => ({
chat: [...state.chat, msg],
}), this.scrollToBottom);
});
}
and in handleSubmit -> I moved the this.socket.emit function call outside. preventing from emit the message twice
handleSubmit(event) {
// Prevent the form to reload the current page.
event.preventDefault();
// Send the new message to the server.
this.socket.emit('message', {
name: this.state.name,
content: this.state.content,
});
this.setState((state) => {
// Update the chat with the user's message and remove the current message.
return {
chat: [...state.chat, {
name: state.name,
content: state.content,
}],
content: '',
};
}, this.scrollToBottom);
}
Hi I have an issue to share with you guys. I got an issue if I wrap the with . You will have your code inside setState run twice. The possible way to fix this is to move the logic outside of setState. I have fix this two setState in App.js.
in componentDidMount -> I moved the msg.reverse() outside setState
and in handleSubmit -> I moved the this.socket.emit function call outside. preventing from emit the message twice
Hope it can help. Thank you Armel.
Hi Yodi, thanks a lot, I have updated the source code on Github and in the article ;)