Home page after refresh

Viewed 41

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>
    </>
  )
}```
1 Answers

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.

Related