5

I'm trying to navigate to admin page if LoggedIn and admin is true while sending props to /admin but this isn't working. Can you help please?



export default function Auth() {


  function login(e) {
    e.preventDefault();
    const data = { email, password };
    axios
      .post("http://localhost:3001/api/Login", data, { withCredentials: true })
      .then((response) => {
      
      if(!!response.data.loggedIn && !!response.data.admin){ return( <Navigate to="/admin"  loggedIn={"response.data.loggedIn"} replace/> )}
     else if(!!response.data.loggedIn && ! !!response.data.admin){ window.location.href = "https://www.dummyweb.com/webmail";}
    else{return(alert("Username or Password is not valid!"))}  
    });
  
  }

  return (
    <div>
    <LogginForm/>
</div>
 )
}
Firas SCMP
  • 461
  • 4
  • 18

4 Answers4

5

To conditionally render content or redirect then you should use the following:

react-router-dom

Since you are trying to use the useNavigate hook I'll assume you are using react-router-dom v6 and will start there.

Version 6

The Redirect component was removed in react-router-dom v6. Use the Navigate component and also specify the replace prop to do a redirect instead of a normal navigation.

export default function Admin(props) {
  return props.isLoggedIn ? (
    <div>
      <Row className={stylesadmin.root}> 
        <Uploader/>
       <ToastContainer/>  
      </Row>
    </div>
  ) : (
    <Navigate to="/Auth" replace />
  );
}

Version 5

Use the Redirect component to redirect to "/Auth".

export default function Admin(props) {
  return props.isLoggedIn ? (
    <div>
      <Row className={stylesadmin.root}> 
        <Uploader/>
       <ToastContainer/>  
      </Row>
    </div>
  ) : (
    <Redirect to="/Auth" />
  );
}

Update

Using imperative navigation/redirect.

Import the useNavigate (v6) / useHistory (v5) hook and issue imperative redirect.

export default function Auth() {
  const navigate = useNavigate();  // v6
  // const history = useHistory(); // v5

  function login(e) {
    e.preventDefault();
    const data = { email, password };

    axios
      .post("http://localhost:3001/api/Login", data, { withCredentials: true })
      .then((response) => {
        if (!!response.data.loggedIn && !!response.data.admin) {
          navigate(
            "/admin",
            {
              replace: true,
              state: { loggedIn: response.data.loggedIn },
            }
          );
          // history.replace(
          //   "/admin",
          //   {
          //     loggedIn: response.data.loggedIn,
          //   }
          // );
        } else if (!!response.data.loggedIn && ! !!response.data.admin) {
          window.location.href = "https://www.dummyweb.com/webmail";
        } else {
          alert("Username or Password is not valid!");
        }  
      });
  }

  return (
    <div>
      <LogginForm/>
    </div>
  );
}
Drew Reese
  • 165,259
  • 14
  • 153
  • 181
  • I used but nothing is happening, the page is staying the same – Firas SCMP Dec 13 '21 at 07:38
  • Well I kinda got what's going on, – Firas SCMP Dec 13 '21 at 07:42
  • @FirasSCMP Have you double checked that `props.isLoggedIn` is false? What if you rendered ***only*** the redirect, i.e. `const Admin = () => ` does it navigate? How/where is this `Admin` component being rendered? – Drew Reese Dec 13 '21 at 07:42
  • First I'm doing an axios.post request to check for the credentials if they are right, then after that if it is right I'm trying to navigate to /admin, but I guess doesn't work outside the return render. right? – Firas SCMP Dec 13 '21 at 07:43
  • I'm gonna post the code please check it – Firas SCMP Dec 13 '21 at 07:44
  • @FirasSCMP correct, you *must* render `Navigate` for it to do anything. If you are trying to navigate imperatively then use the `useNavigate` hook and at the end of the axios call do `navigate("/Auth")`... after `const navigate = useNavigate()` in the component body OFC> – Drew Reese Dec 13 '21 at 07:45
  • yes but the main purpose is to send props with the navigate that's why I used it the declarative way, is there a way to send props with navigate() ? – Firas SCMP Dec 13 '21 at 07:49
  • I've changed the code above – Firas SCMP Dec 13 '21 at 07:51
  • @FirasSCMP Sending "props", no, not really, but you can certainly send data in route state. It can be accessed on receiving routes/components on the `location` object. – Drew Reese Dec 13 '21 at 08:04
  • 1
    BIG THANKS, I used the {state} to pass some data it worked. – Firas SCMP Dec 13 '21 at 08:10
  • @FirasSCMP Great! Just FYI, you can also send route state with `Navigate` and `Link` components on the `state` prop in v6, or as part of the `to` prop object of the `Link` in v5, i.e. `test`. – Drew Reese Dec 13 '21 at 08:16
  • Great to know! Thanks – Firas SCMP Dec 13 '21 at 08:56
3

You can use react-router Redirect component

return <>{props.isLoggedIn ?  (<div>
   <Row className={stylesadmin.root}> 
     <Uploader/>
     <ToastContainer/>  
   </Row>
 </div>) : <Redirect to='/Auth'/> }</>
}
Saeed Shamloo
  • 6,199
  • 1
  • 7
  • 18
2

you can use either Redirect component or use useHistory hook from react-router-dom

HexaCrop
  • 3,863
  • 2
  • 23
  • 50
0
import { useNavigate } from 'react-router-dom';
export default function Auth() {

  let navigate = useNavigate();
  function login(e) {
    e.preventDefault();
    const data = { email, password };
    axios
      .post("http://localhost:3001/api/Login", data, { withCredentials: true })
      .then((response) => {
      
      if(!!response.data.loggedIn && !!response.data.admin){ return(  navigate( "/admin" , { state:{loggedIn:response.data.loggedIn}} )}
     else if(!!response.data.loggedIn && ! !!response.data.admin){ window.location.href = "https://www.dummyweb.com/webmail";}
    else{return(alert("Username or Password is not valid!"))}  
    });
  
  }

  return (
    <div>
    <LogginForm/>
</div>
 )
}

and on the admin page I handle it as follows

export default function Admin() {
  const {state} = useLocation();
 const { loggedIn} = state;

return(
loggedIn?
(<whatever/>):(<whatever2/>)
 )
}

This works perfectly

Firas SCMP
  • 461
  • 4
  • 18