U
U
undying2342021-08-17 17:59:54
Node.js
undying234, 2021-08-17 17:59:54

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

Here is the code in React.
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()

Here is the code from the server.
When you type Dima and press Enter, the console should display Dima, but it outputs this:611bcedfbabd5516405237.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexandroppolus, 2021-08-17
@Alexandroppolus

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 question

Ask a Question

731 491 924 answers to any question