Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

250
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda