im building a chat app with mern and socket.io, i tried to emit with callback but it emit function not value and when i delete setList(l=>[...l,data]) it emit (first problem). And the second problem, when i recieve the message and push it to list twice (useEffect).
Client side:
import React,{ useState,useEffect } from 'react';
import socketIOClient from "socket.io-client";
function Room(props) {
const [message,setMessage]=useState('');
const [list, setList] = useState([]);
const ENDPOINT = "http://localhost:5000";
const socket = socketIOClient(ENDPOINT, {
credentials: true
});
const sendMessage=(e)=>{
e.preventDefault();
let data=message;
//the first problem is here
socket.emit('send',(data)=>{
setList(l=>[...l,message])
});
}
useEffect(()=>{
//the second problem is here
socket.on('rec',(data)=>{
setList(l=>[...l,data])
})
},[])
return (
<div>
<div>
{list!==[] && list!==null && list.map((el,i)=>{
return <p key={i}>{el}</p>
})}
</div>
<div>
<form>
<input value={message} onChange={e=>setMessage(e.target.value)} />
<button onClick={sendMessage}>Send</button>
</form>
</div>
</div>
)
}
export default Room;
Server Side:
const io = new Server(server, { cors: { origin: '*'}});
app.use((req,res,next)=>{
res.header("Access-Control-Allow-Credentials", true);
next();
})
dotenv.config();
io.on("connection", (socket) => {
socket.emit('greeting', {
greeting: 'Hello Client'
})
socket.on("send", (data) => {
io.emit("rec", data);
console.log(data)
});
});
server.listen(process.env.PORT, err => err?console.log('server error'):console.log(`server is running on PORT ${process.env.PORT}`));
CodePudding user response:
//the first problem is here
socket.emit('send',(data)=>{
setList(l=>[...l,message])
});
has to be
socket.emit('send', message, (data)=>{
setList(l=>[...l,message])
});
(you missed the argument, see https://socket.io/docs/v4/client-api/#socketemiteventname-args)
2)
useEffect(()=>{
//the second problem is here
socket.on('rec',(data)=>{
setList(l=>[...l,data])
})
},[])
it's not really a problem, because you add the same message here and in sendMessage, by using setList twice. I suppose for the chat app you need to change io.emit("rec", data);
with a different response.