Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

178
Vistas
How to store socket on localStorage/use socket on different components on vanilla ReactJS for use in different components socket.io?

I want to store the socket so I can use it in different components. When I first set the socket on socket.io after login, I set the socket as a state under "socket" state and then store it on localStorage.

useEffect(() => {
        if(!socket) {
            setSocket(io(backendLink));
        };
    }, []) 

useEffect(() => {
        socket?.emit("newUser", localStorage.getItem('authToken'));
        localStorage.setItem('socket', JSON.stringify(socket));
    }, [socket])

Then in different components, where I did not initially set the socket. I use logic like this:

useEffect(() => {
        if(!socket) socket = localStorage.getItem('socket');
        socket.emit(...)
}, [userID])

Above, if the socket passed as props that was stored in state is null, i restore the socket from localStorage and use it to emit. However, I get Uncaught TypeError: Converting circular structure to JSON.

From what I understood, this is because I used JSON.stringify on something that cannot be converted and stored on localStorage this way i.e socket. I want to use vanilla reactjs to use the socket across as different files from the file i used setSocket(io(backendLink)). How to use socket.io across different components with vanilla reactJS(no context, completely vanilla)?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You should not stringify such objects, if you want to reference it across your application, you need to just to place it inside a React context after you saved it in the state. That way you can access it wherever you want across your application. There are other options too, but that's the safer one.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda