Home > Back-end >  How to store socket on localStorage/use socket on different components on vanilla ReactJS for use in
How to store socket on localStorage/use socket on different components on vanilla ReactJS for use in

Time:04-19

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)?

CodePudding user response:

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.

  • Related