Answer the question
In order to leave comments, you need to log in
Can you help me figure out weirdness in socket.io and React?
const Home = () => {
const [msg, setMsg] = useState('')
const socket = io.connect('http://localhost:5000', { autoConnect: true })
function enterSendMsg(e){
setMsg(e.target.value)
document.addEventListener('keydown', (event) =>{
if(event.key == "Enter"){
socket.emit('send msg', msg)
setMsg('')
}
})
}
return (
<div>
<Navbar />
<div className="chatArea">
<ul className="messages"></ul>
</div>
<div></div>
<MyInput
value={msg}
placeholder='Пиши сюда'
type='text'
onChange={(e)=> enterSendMsg(e) }
/>
</div>
)
}
export default Home
require('dotenv').config()
const express = require('express')
const app = express()
const server = require('http').createServer(app)
const io = require('socket.io')(server, {
cors: {
origin: "http://localhost:3000",
}})
const PORT = process.env.PORT || 6000
app.use(express.json())
io.sockets.on('connection', function(socket){
socket.on('send msg', function(data){
console.log(data)
})
})
const start = async ()=>{
try {
server.listen(PORT, ()=> console.log(`Server on ${PORT}`))
} catch (e) {
console.log(e)
}
}
start()
Answer the question
In order to leave comments, you need to log in
A new socket is created for each rerender.
It is possible like this:
const [socket] = useState(() => io.connect('http://localhost:5000', { autoConnect: true }));
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question