How to display the lastmessage sent when user is not inside the chat?

I’ve just got same problem yesterday. But now it has been fixed. This one should works

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

const Chatbox = () => {
  const [chats, setChats] = useState([])
  const [message, setMessage] = useState('')
  const socketClientRef = useRef()

  useEffect(() => {
    const client = socket("http://localhost:3002");
    client.on("connect", () => {
      console.log('connected')
    })
    client.on("disconnect", () => {
      console.log('diconnected')
    });
    client.on("chat", message => {
      setChats(prevChats => [...prevChats, message])
      // INSTEAD OF:
      // setChats([...chats, message])
    });
    socketClientRef.current = client
    return () => {
      client.removeAllListeners()
    }
  }, [])

  const handleSend = async () => {
    socketClientRef.current.emit('chat', {
      room: `event-${eventId}`,
      message
    })
    setMessage('')
  }


  return (
    <div>
      <div>
        <h1>Messages</h1>
        {chats.map(chat => (
          <div>{chat}</div>
        ))}
      </div>
      <div>
        <input value={message} onChange={e => setMessage(e.target.value)} />
        <button onClick={handleSend}>Send</button>
      </div>
    </div>
  )
}

Leave a Comment