Home > Mobile >  React with Socket.io first request in useEffect
React with Socket.io first request in useEffect

Time:11-15

I am using Socket.io in react app. I would like to do first request immediately after app loads so I put my first emit in useEffect hook:

useEffect(() => {
    socket.emit("getCollectionsAndVolumes", socket.id);
  }, []);

but it doesn't work. It does not do any request. So I realized that a problem is because maybe socket is not connected yet so I put little timeout like:

useEffect(() => {
    const initialGetTimeout = setTimeout(() => {
      clearTimeout(initialGetTimeout);
    }, 1000);
  })

and it works but it is only a workaround, how should I trigger first request right after app loads? Is there any other way to do that in React?

CodePudding user response:

Add a parameter which gets changed when socket is connected as a dependency for useEffect React.useEffect(()=>{},[dependencies]);, if there is no such parameter, then try creating a state that maintains if socket is connected or not.

CodePudding user response:

I fixed that by using:

socket.on("connect", () => {
  socket.emit("getCollectionsAndVolumes", socket.id);
});

so when it is true it immediately executes request

  • Related