Claire
Claire

Reputation: 113

react private router redirect

I have an api to check if user is logged in or not, and I want to redirect page by checking the response code from api, not sure how to write it?

api:

 case 'loggedin':
                $result = $_SESSION['sessionOBJ']->logged_in();
                if($result == true){
                    echo json_encode($result); //login
                    http_response_code(200); 
                }else{
                    http_response_code(401); //not login
                } 
            break;

privateRouter:

import React from "react";
import { Route, Redirect } from "react-router-dom";
// token
import { getToken } from "../../utils/session";


const PrivateRouter =({component: Component, ...rest}) => {
    return (
        <Route
          {...rest}
          render={routeProps => (
          getToken() ? <Component {...routeProps} /> : <Redirect to="/" />    // "/" is login page path
          //getToken() === 200 ? <Component {...routeProps} /> : <Redirect to="/" />   
          )}
        />
      );
}

export default PrivateRouter;

and the getToken : I want to redirect to private page when reponse code is 200, otherwise stay in the login page.

export function getToken(){
    return axios.get(
                `http://localhost:80/doctorbooking/api/api?action=loggedin`,
                {withCredentials: true},
    ) 
}

Upvotes: 0

Views: 31

Answers (1)

shennan
shennan

Reputation: 11656

Looking at the documentation, it seems that axios.get returns a Promise. This means you'll only know if the user is authenticated when that Promise has been fulfilled. In that case, you'll need to update the component when this happens. Try something like this:

import React, {useState, useEffect} from "react";
import { Route, Redirect } from "react-router-dom";
import { getToken } from "../../utils/session";

const PrivateRouter = ({component: Component, ...rest}) => {

  const [ isAuthenticated, setIsAuthenticated ] = useState(null)

  useEffect(() => {

    getToken()
      .then(() => setIsAuthenticated(true))
      .catch(() => setIsAuthenticated(false))

  }, [])

  return (
    <Route
      {...rest}
      render={routeProps => (
        isAuthenticated === null
          ? null
          : isAuthenticated === false
            ? <Redirect to="/" />
            : <Component {...routeProps} />
      )}
    />
  );
}

export default PrivateRouter;

In the above, I'm updating the isAuthenticated state only when the Promise has been fulfilled. If the isAuthenticated is set to null (which it is initially), it means we're still waiting on the Promise result. In that case, we simply render null for React (which equates to nothing). You could, instead, render a loading component.

Upvotes: 2

Related Questions