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

114
Views
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 answers
Answer question

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 Report
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!