0

Does the following code create duplicate on.message listeners ? when i execute on.message once, the payloads array takes it's initial value each time

export default function ProjectChat() {

    const { id: projectId } = useParams()

    const [payloads, setPayloads] = useState([])
    const [messageBody, setMessageBody] = useState('')
    const [webSocket, setWebSocket] = useState(null)

    // Create the connection
    useEffect(() => {
        const url = `ws://localhost:3000/ws/${projectId}`;
        const ws = new WebSocket(url);
        setWebSocket(ws)

        return () => ws.close()
    }, [])

    useEffect(() => {
        if (webSocket !== null) {
            webSocket.onmessage = e => {
                const payload = JSON.parse(e.data);
                const allMessages = [...payloads, payload]
                setPayloads(allMessages)
            }
        }
    }, [webSocket, payloads])

    return <p>jsx</p>
}
  • Try using [functional update](https://stackoverflow.com/questions/57828368/why-react-usestate-with-functional-update-form-is-needed) and remove `payloads` from deps array: `setPayloads(curr => [...curr, ...payload])` – Sergey Sosunov Feb 19 '23 at 17:22

1 Answers1

0

You can't create duplicate listeners with on.message. Every time you define on.message, you're over-writing the previous listener.

The addListener is the method which can lead to multiple listeners. In that case, you would want to run removeEventListener() on the listener you created inside your component's unmount phase return () => removeEvenListener(...).

Wesley LeMahieu
  • 2,296
  • 1
  • 12
  • 8