im creating a simple chat application using reactJS and socket.io for webSocket,but when i got a new message from server to add it to the message array state, is reseted to initial value which is an empty Array:
import React, { useState, useEffect } from "react";
import socketIOClient from "socket.io-client";
let socket;
export default () => {
const [messages,setMessages]=useState([]);
useEffect(() => {
socket = socketIOClient("https://localhost:5000");;
socket.on("resp-chat-user", data => {
setMessages([{
message:data.message,
}]);;
})
return () => socket.close();
}, []);
const SendMessage=(msg)=>{
if(msg && msg!="")
{
socket.emit("req-chat-user", {
message:msg,
to: SOCKET_ID
});
setMessages([...messages,{
message:msg
}])
}
}
return (
<>
<ul>
{messages.map(msg=>(
<li>{msg}</li>
))}
</ul>
<button type="submit" onClick={()=>SendMessage("HOLA")}>send</button>
</>
);
};
the way that i update state inside socket listener is wrong, i should use:
setMessages(messages => [ ...messages, {
type:"other",
message:data.message,
} ]);
insead of
setMessages([ ...messages, {
type:"other",
message:data.message,
} ]);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.