0

I want to open the page up and if I'm not signed in I want it to immediately redirect me to a sign up page. When I open up the app I don't get redirected despite not being signed in, I get sent to the home page where it says welcome blank where it should say welcome user.username (whatever that value is set to) so why is the if statement not working?.I'm new to the react router dom so any help if appreciated. The log in does work and by changing state I can get the desired result, but I want the url to change too.

import SignIn from './components/SignIn';
import Home from './components/Home';
import { BrowserRouter as Router, Route, Routes, Navigate } from 'react-router-dom';
import './App.css';
import { useState, useEffect } from 'react';


function App() {

  const guestUser = {
    username: "guest",
    password: "guest",
  }

  const [user, setUser] = useState({username: "", password: ""})
  const [error, setError] = useState("");
  

  const Login = details => {
      console.log(details);
      if(details.username == guestUser.username && details.password == guestUser.password) {
        console.log("Logged in as guest");
        setUser({
          username: details.username,
          
        })
      } else {
        console.log("details do not match");
        setError("Details do not match.")

      }
  }

  const Logout = () => {
      console.log("logout");
  }



  return (

    <div className="App">
      
      <Router>
        <Routes>
          
          <Route path="/Login" element={<Intro Login={Login} Logout={Logout} error={error}/>} />
          <Route path="/Home" element={<Home user={user}/>}/>
          <Route path="" element={<Home user={user}/>}/>
          
          
          
      
      
          {(user.username !== "") ? ( <Route element={<Navigate to="/Home"/>}/>
          ) : (
            <Route element={<Navigate to="/Login"/>}/>
            
            
          )}
        </Routes>

      </Router>
        
    </div>
     
 
    
  );
}

export default App;
SebR
  • 67
  • 1
  • 8

2 Answers2

0

I think setting the code to:

 {user.username ? ( <Route element={<Navigate to="/Home"/>}/>
      ) : (
        <Route element={<Navigate to="/Login"/>}/>
        
        
      )}

may help.

If user.username is false it'll redirect to Login, if the string has content like "x" it'll return true and go Home.

Edit: Typo

Gieto
  • 27
  • 1
  • 4
  • I tried that and it's not working, the if statement I put should work as it worked before I added the routes, I'm just a noob with react router dom right now so I suspect I'm doing something wrong with the routing – SebR May 19 '22 at 10:29
  • if it was working before then what did you have instead of the routing? logs? try to make a button to see if the routing is working on click. this is what I use on my code: `const renderApp = () => { return isSignedIn ? : };` I call it on my app to separate the different satcks, it's react native, but you get the idea – Gieto May 19 '22 at 10:54
  • I've got it working so it now redirects me to the login page this is the new code: ``` : }/>``` so I put the logic in the element part of the Route, but when I sign in it wont change the page back any pointers? – SebR May 19 '22 at 11:20
  • You'd need to update the state again if you want to be able to go back, maybe set a signOut button on the homepage that sets the user.username to "" just for testing. Imo what you're trying to isn't the best way to do it – Gieto May 20 '22 at 09:21
0

I solved it. Now the user will automatically get redirected to the home page by putting the if statement logic inside the element part of the route. After that I got the problem that I wouldn't be redirected after signing in despite the console log confirming I had logged in. This was because I didn't put a navigate function after.

To make it look cleaner I put the tag in the index.js file instead of the app.js file (the file show below), so that all child components have access to the routing.

Also, if I refresh the page my log in info is lost and technically I'm signed out again but I've found a tutorial that says that you will need to store these state variables in local storage using useEffect so the browser remembers you are signed in despite refreshing so that will be the next step.

import Intro from './components/Intro';
import SignIn from './components/SignIn';
import Home from './components/Home';
import { BrowserRouter as Router, Route, Routes, Navigate, useParams, useNavigate } from 'react-router-dom';
import './App.css';
import { useState, useEffect } from 'react';


function App() {

  const guestUser = {
    username: "guest",
    password: "guest",
  }

  const [user, setUser] = useState({username: "", password: ""})
  const [error, setError] = useState("");

  const navigate = useNavigate()

  
  

  const Login = details => {
      console.log(details);
      if(details.username == guestUser.username && details.password == guestUser.password) {
        console.log("Logged in as guest");
        setUser({
          username: details.username,    
        });
        navigate('/Home')

        
        
      } else {
        console.log("details do not match");
        setError("Details do not match.")

      }
  }

  const Logout = () => {
      console.log("logout");
  }



  return (

    <div className="App">
      
      <Routes>    
        <Route path="/Login" element={<Intro Login={Login} Logout={Logout} error={error}/>} />
        <Route path="/Home" element={<Home user={user}/>}/>
        <Route path="" element={user.username !== "" ? <Navigate to ="/Home" /> :
          <Navigate to ="/Login"/>}/>
          
      </Routes>        
    </div>
     
 
    
  );
}

export default App;
SebR
  • 67
  • 1
  • 8