I am integrating web sockets into React with Django in back-end.
I am able to send messages, and receive the new messages from the back-end.
The problem is that after sending 3 or 4 messages, the previous messages are getting replaced by the new messages in the front-end, but all is fine in the back-end, and in fact everything works normally after I refresh.
How to properly update state for situations like this?
Edit:
The main problem which I found now is, when I send a chat, the state gets updated multiple times, and its length changes everytime and the screen flutters a lot.
slice
name: 'chat',
initialState: {
chatMessages: [],
}
reducers: {
setChatMessages(state, action) {
const chatmessages = action.payload;
return {...state, chatMessages:chatmessages};
},
}
chat
const chatMessagesSelector = useSelector(selectChats);
const chatMessages = chatMessagesSelector?.chatMessages
chatSocket.onmessage = (e) => {
var data = JSON.parse(e.data)
var message = {message: data.message, user: data.user,
timestamp: data.timestamp};
//console.log(message)
let updatedMessages = [...chatMessages];
updatedMessages.push(message);
dispatch(setChatMessages(updatedMessages));
}
This is the chatMessages object logged above the updatedMessages.
Array(1)
0: {user: "testuser", message: "check!", timestamp: "2021-03-09T09:15:09.408717+01:00}
length: 1