Search code examples
reactjsreact-routeramazon-cognitoreact-router-domaws-amplify

How to create a Protected Route with Promises


I'm using a hook to protect my routes. The problem that I'm encountering is that the call to check for the user's auth status returns a Promise, so the hook returns the default value, which is a and then the auth status is no longer useful since we already redirected.

So how can I wait to return from the hook until the auth check is done? Here's my code:

export function ProtectedRoute(props){

const [loggedIn, setLoggedIn] = useState(false);

// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
    async function fetchUser() {
        let user = null;

        try {
            user = await Auth.currentAuthenticatedUser()
            if (user) {
                setLoggedIn(true);
            } else
            {
                setLoggedIn(false);
            }
        } catch (e) {
            setLoggedIn(false);
        }
    }
    fetchUser()
});

console.log("ProtectedRoute: returning " + loggedIn);
if (loggedIn)
    return props.component
else
    return <Redirect to={{pathname: '/login'}}/>

}


Solution

  • Found a solution...had to default to 'true' for isAuthenticated and then redirect if that wasn't the case (the Redirect seemed to be breaking the logic for me in my initial code)

    export function ProtectedRoute({ component: Component, ...rest }){
    
    const [isAuthenticated, setLoggedIn] = useState(true);
    useEffect(() => {
        (async () => {
            let user = null;
    
            try {
                user = await Auth.currentAuthenticatedUser()
                if (user) {
                    setLoggedIn(true);
                } else
                {
                    setLoggedIn(false);
                }
            } catch (e) {
                setLoggedIn(false);
            }
        })();
    });
    
    return (
        <Route
            {...rest}
            render={props =>
                isAuthenticated ? <Component {...props} /> : <Redirect to="/login" />
            }
        />
    );
    

    }