React with Socket.io first request in useEffect


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?

Source: React – Stack Overflow

November 14, 2021
Category : News
Tags: reactjs | socket.io | sockets | use-effect

Leave a Reply

Your email address will not be published. Required fields are marked *

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.