Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

115
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda