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

116
Visualizações
Home page after refresh

In my react app while refreshing on the pages that require being loggedIn it takes me to homepage. Information that someone is loggedIn stored in state which gets updated on base of value of auth true/false (which is stored in sessionstorage). How can I force react to first change state (its default is false) before rendering component?

  const [loggedIn, setLoggedIn] = useState(false)
  const [user, setUser] = useState("temp");

  Axios.defaults.withCredentials=true;
  useEffect(()=>{
    Axios.get("http://localhost:3001/check")
    .then((response)=>{
      sessionStorage.setItem('auth', JSON.stringify(response.data["Authorized"]));
    });
    if(sessionStorage.getItem("auth")==="true"){
      setLoggedIn(true)
    }else{
      setLoggedIn(false)
    }
  })

  return (
    <>
      {loggedIn ? <LoggedInNavbar user={user}  /> : <Navbar/>}
      <AnimatePresence>
        <Routes location={location} key={location.pathname}>
          <Route 
            path="/" 
            element={<Home/>}/>
          <Route 
            path="/logowanie/:state" 
            element={loggedIn ? <Navigate to="/"/> : <LogIn/>}/>
          <Route 
            path="/rejestracja" 
            element={loggedIn ? <Navigate to="/"/> : <SignUp/>}/>
          <Route 
            path="/regulamin" 
            element={<Rules/>}/>
          <Route 
            path="/dashboard/:username" 
            element={loggedIn ? <Dashboard  user={user}/> : <Navigate to="/"/>}/>
        </Routes>
      </AnimatePresence>
    </>
  )
}```
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I see two issues in your code:

useEffect(()=>{
    Axios.get("http://localhost:3001/check")
    .then((response)=>{
      sessionStorage.setItem('auth', 
      JSON.stringify(response.data["Authorized"]));
    });
    
    // this part of code is executed BEFORE the Axios response
    // Axios.get is async and the `if` condition does not wait for
    // Axios response to be processed.
    if(sessionStorage.getItem("auth")==="true"){
      setLoggedIn(true)
    }else{
      setLoggedIn(false)
    }
    })

The correct use of this should like this:

useEffect(()=>{
    Axios.get("http://localhost:3001/check")
    .then((response)=>{
      sessionStorage.setItem('auth', 
      JSON.stringify(response.data["Authorized"]));
      if(response.data["Authorized"])){
        setLoggedIn(true)
      }else{
        setLoggedIn(false)
      }
    });
    }, []) // <-- attention, you have to give dependency list,
    // so this useEffect is used only on first render.

Another is the main pillar of your problem:

         <Route 
            path="/dashboard/:username" 
            element={loggedIn ? <Dashboard  user={user}/> : <Navigate to="/"/>}/>

Don't redirect user, simply render the Home path, if the user is not logged in.

         <Route 
            path="/dashboard/:username" 
            element={loggedIn ? <Dashboard  user={user}/> : <Home />}/>

With this logic, you will use the loggedIn state the proper way: as soon as React will get true in loggedIn state, user will get the Dashboard element. (Or you can take him directly to LogIn element.) What more - as soon as user logs in, he is taken back to the path, he was previously looking for - because it stays in URL.

about 4 years ago · Juan Pablo Isaza Relatório
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