How do I get this protected route working?

Viewed 322

So I am working on setting up a protected route in react. I am using Express and Passport for my authentication. I setup the following code to setup the protected route, but the checkLogin() function (which produces true if logged in and false if not) at the top which does work if I take it out of this code and execute it manually does not execute in this use case. (I think its because the promise is still pending, but I am not sure how to make it async I just keep getting errors)

The Code:

import React from 'react';
import { Route, Redirect} from 'react-router-dom';
import axios from 'axios';

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

const checkLogin = () => {
    axios({
        type: 'get',
        url: 'http://localhost:5000/checklogin',
        withCredentials: true,
    }).then((response) => {
        console.log(response);
    }).catch((error) => {
        console.log(error);
    })

}

return(
    <Route
        {...rest}
        render={(props) => 
            checkLogin() === true ? (
                <Component {...props} />
            ) : (
                <Redirect to='/' />
            )
        }

    />

)
};

export default RouteGuard;

Any ideas on getting this to work, or a better way to go about it? I just want to send a post to my backend and return true or false to check that the user is logged in and then protect routes based on that.

Update:

I now changed it to use useEffect() as well as set some state as suggested, but the isLoggedIn state is not being set before the if statement tries to check if its set to true.

Updated Code:

import React, { useState, useEffect } from 'react';
import { Route, Redirect} from 'react-router-dom';
import axios from 'axios';

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

const [isLoggedIn, setIsLoggedIn] = useState()

useEffect(() => {
        const getStatus = async () => {
        const result = await axios({
            type: 'get',
            url: 'http://localhost:5000/checklogin',
            withCredentials: true,
        });
            
            setIsLoggedIn(result);
        };

        getStatus();

    }, []);

return (
    <Route
        {...rest}
        render={(props) => 
            isLoggedIn === true ? (
                <Component {...props} />
            ) : (
                <Redirect to='/' />
            )
        }

    />

)
};

export default RouteGuard;
0 Answers
Related