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