0

In my app, I am emitting a socket event whenever the user receives a new message and I try to display in front end react using socket.io-client.

My react code is as follows

import React, { useState, useEffect, useContext, useRef } from "react"
import io from "socket.io-client"
import StateContext from "../../../StateContext"

const Received = () => {
  const appState = useContext(StateContext)

  const [inbox, setInbox] = useState([])
  const ENDPOINT = "http://localhost:3008"

  let socket = useRef()

  const fetchInbox = () => {
    axios.post("/messages")
      .then((res) => {
        console.log(res.data)
        setInbox(res.data)
      })
      .catch((err) => {
        console.log(err)
      })
  }

  useEffect(() => {
    fetchInbox() 
  }, [])


  useEffect(() => {
    console.log("connection created")

    socket.current = io(ENDPOINT, {
      withCredentials: true
    });

    socket.current.on("connect", () => {
      console.log(socket.current.id)
      socket.current.emit('join', { email: appState.email })
    })

    socket.current.once("new message", (msg) => {
      console.log(msg)
      setInbox(oldMsgs => [...oldMsgs, msg])
    })

    socket.current.on("disconnect", () => {
      console.log("disconnected")
    })

    return () => socket.current.disconnect();

  }, [ENDPOINT])

and my server-side code I am passing socket instance from app.js to message.js file and emitting socket event. In messages.js file

const emit_messages = (user_ids, new_message) => {
    try {
        user_ids.map((userid) => {
            io.sockets.in(userid).emit("new message", new_message)
        })
    }
    catch (err) {
       console.log(err)
    }
}

My react code is rendering multiple times, even I have declared dependencies in the useEfect hook. My problem is similar to the one stated in this stackoverflow question socket.io emits multiple times

socket.current.once is firing only for one request. For subsequent requests, it is not being fired.

Can someone help me to solve this issue?

and what is the right way to use socket.io in react and why the component is rendering many times

Any help is appreciated. Thanks ...

Lohitha Y
  • 1
  • 5

0 Answers0