PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, August 5, 2022

[FIXED] How to use socket.io with localStorage item as query value?

 August 05, 2022     local-storage, reactjs, socket.io     No comments   

Issue

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.


Solution

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.



Answered By - Jlove
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing