Home > database >  How to use socket.io with localStorage item as query value?
How to use socket.io with localStorage item as query value?

Time:06-24

Objective


I want to pass a token from localStorage to verify user's identity during a socket.io connection.
For that I follow the documentation and initialize io() outside of MyComponent and add the token as a query :

const token = localStorage.getItem('refresh_token');
const test = "hello world";

const socket = io(
  process.env.REACT_APP_API_ADDRESS_HOST,
  {
    query: { token }, // <-- null
  },
);

console.log(token) // <-- null
console.log(test) // <-- "hello world"


export const MyComponent = () => {
    ...
}

Issue


The problem is since this code is outside of MyComponent it will run during app initialization, at which point the 'refresh_token' isn't even in localStorage yet, so it is null unless I manually refresh the page.


Attempts


I thought about initializing io() inside MyComponent but I don't think I can, else it would either run on every render, or if I put it inside a useEffect() then it won't be accessible inside other functions/useEffects.

CodePudding user response:

As I began typing this answer, I realized that the best situation is likely to combine state & useEffect:

const [socket, setSocket] = useState(null)

useEffect(() => {
  setSocket(io(
    process.env.REACT_APP_API_ADDRESS_HOST,
    {
      query: { token },
    },
  ))
}, [token])


export const MyComponent = () => {
    ...
}

My previous comment was misleading so I'll delete that.

  • Related