0

when i try access dashboard by lnik (http://localhost:3001/dashboard) in browser it's navigate me back to /signin as it should, but if I logging by correct user it doesn't change route to /dashboard. Connection with "serwer" is working properly, but route stays in /signin. It's early stage so server is only working for one user as yet. I would like someone to point out my mistake.

There is discussed part of main App:(all libraries are correctly imported)

useEffect (() => {
    fetch('http://localhost:3000')
        .then((response) => response.json())
            .then(console.log)})

const [user,setUser] = useState(false);
const isUserValid=(user)=>{
    setUser(user);
}


    return(
        <Routes>
            <Route path="/signin" element={<Signin userValue={isUserValid}/>}/>
            <Route path="/register" element={<Register />} />
            <Route path="/dashboard" element={<PrivateRoute userValid={user}/>}>
                <Route  element={<Dashboard />} path="/dashboard"/>
            </Route>
        </Routes>
    )

Server (nodejs with express.json and cors):

app.post('/signin', (req, res) => {
if(req.body.email === database.users[0].email &&
    req.body.password === database.users[0].password){
    res.json('success');
} else {
    res.status(400).json('error');
}})

Private Route module:

const PrivateRoute =({children, userValid})=>{
   return userValid ? children: <Navigate to="/signin" />;
}

export default PrivateRoute;

Sign in module (form working properly, gets values ​​from inputs and sends to server then gets response):

const Signin =({userValue})=> {
    const [userEmail,setUserEmail] = useState('');
    const [userPassword,setUserPassword] = useState('');
  
    const onEmailChange = (event) => {
      setUserEmail(event.target.value);
    }
  
    const onPasswordChange = (event) => {
      setUserPassword(event.target.value);
    }
  
    const onSubmitSignIn = () => {
      fetch('http://localhost:3000/signin', {
        method: 'post',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({
          email: userEmail,
          password: userPassword
        })
      })
        .then(response => response.json())
        .then(data => {
            if(data === 'success'){
                userValue(true);
                window.location.href = "/dashboard";
            }
        })
        }
Drew Reese
  • 165,259
  • 14
  • 153
  • 181
  • React Router 6 uses a component called `Outlet` to render nested routes, `PrivateRoute` should use this instead of children. – Jacob Smit Aug 15 '22 at 23:53
  • Still doesn't working. I think the problem may be with `Route` in App , because `signin` module changes user state to true but `PrivateRoute` does not return /dashboard route. – Norbert Dąbrowski Aug 16 '22 at 00:13
  • In addition to fixing the `PrivateRoute` component to render an `Outlet`, don't use `window.location.href = "/dashboard";` is this reloads the page, and the entire React app. Any saved state will be lost. Use `navigate` to issue an imperative redirect to the dashboard route. Also, don't use an initial `user` state value that matches either the authenticated ***or*** unauthenticated states. You can conditionally render a loading indicator while waiting for the auth status to resolve. – Drew Reese Aug 16 '22 at 00:15

0 Answers0