Home > database >  app don´t update useEffect Socket.io/react
app don´t update useEffect Socket.io/react

Time:04-24

i have a problem whit a simple chat app, when i send a message in the other clients don´t see the update, this is the backend

const express = require('express')
const cors = require('cors')
const http = require('http')
const {Server} = require('socket.io')

const app = express()
app.use(cors())

const server = http.createServer(app)
const io = new Server(server,{cors:'http://localhost:3000'})

let mensaje

io.on('connection',socket =>{
    socket.on('new',data =>{
        mensaje = data
        socket.emit('mensaje',mensaje)
    })
})

server.listen(3001,() =>{
    console.log('Server online')
})

and de frontend

import {io} from 'socket.io-client'
import {useState, useEffect} from 'react'

const socket = io('http://localhost:3001')


function App() {
  const [user,set_user] = useState('')
  const [mensaje,set_mensaje] = useState('')
  const [mensajes,set_mensajes] = useState('')

  const handle_input = ({target}) =>{
    set_user(target.value)
  }
  const handle_message = ({target}) =>{
    set_mensaje(target.value)
  }
  const handle_click = () => {
    socket.emit('new',{user,mensaje})
  }

  useEffect(() => {
    socket.on('mensaje',data =>{
      set_mensajes(data)
    })
  }, [socket])

  return (
    <main>
      <div>
        <h1>Hi {user}</h1>
        <input type="text" onChange={handle_input}/>
        <h2>what do u want to say today</h2>
        <input type="text" onChange={handle_message}/>
        <button onClick={handle_click}>Send</button>
      </div>
      <div>
        <h1>{mensajes.user}</h1>
        <p>{mensajes.mensaje}</p>
        <br/>
      </div>
    </main>
  )
}

export default App;

they are the version from all

"express": "^4.17.3", "socket.io": "^4.4.1", "react": "^18.0.0", "socket.io-client": "^4.4.1",

i found if add

...
socket.emit('mensaje',mensaje)
socket.broadcast.emit('mensaje',mensaje)

in the backend works well, but i khow that is´nt the correct way to do it

CodePudding user response:

You should be using io.emit('mensaje',mensaje) on your backend rather than socket.emit('mensaje',mensaje). See here.

CodePudding user response:

you dont need to use useEffect here. Use just

socket.on('mensaje',data =>{
  set_mensajes(data)
})
  • Related