Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

248
Views
Get token from session storage before page renders in React

Previously I was using local storage to store the tokens so that they can be shared among all the tabs, but I needed a requirement to delete the tokens when the user closes all the tabs or the entire browser, so I switched to session storage to save the token and used storage event listener to share it among all the tabs, The functionality is working as expected, but I could see an edge case here is, when I login successfully, and opens a new tab and try to open the application, it redirects to login page because when the page renders at first it won't have token in session storage, after few seconds only we will get the token from the logged-in tab.

My Requirement is - How can I get the data from the already opened tab session storage and store them in the newly opened tab before the page gets rendered?

According to the code, it redirects to the login page since it doesn't have tokens during page render, but after that, I can see the tokens in session storage, so how can I solve this issue, so that on-page render itself I can have the token and redirect to home page.

Here is the code,

App.js

function App(){
return(
//All other route codes
<Route exact render={() => getUserToken() ? <Redirect to="/home"/> : <Redirect to="/login"/> } />
)
}

service.js

export const getUserToken = () => {
const token = sessionStorage.getItem("token");
return token
}

apps.component.js

 // To trigger the storage event listener on every page render
    useEffect(() => {
    localStorage.setItem("REQUEST_TOKEN",Date.now().toString());
    localStorage.removeItem("REQUEST_TOKEN")
    },[])
    
    // To get the token from opened tab and store them in newly opened tab session storage
    useEffect(() => {
    window.addEventListener('storage', () => {
    const tokenCreds = sessionStorage.getItem("token")
    if(event.key === "REQUEST_TOKEN" && tokenCreds){
    sessionStorage.setItem("token",event.newValue)
    }
    })
    },[])

Is there any way to get the token before the new tab renders completely so that it can redirect to the home page?

Thanks in advance!!!

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!