-1

Hello im trying to create a private Route

PrivateRoute.js

const PrivateRoute = ({ children, ...rest }) => {
    return (
        <Route
            {...rest}
            render={({ location }) =>
                Authenticate() ? (
                    children
                ) : (
                    <Redirect
                        to={{
                            pathname: "/login",
                            state: { from: location },
                        }}
                    />
                )
            }
        />
    );
};
export default PrivateRoute;

When I request a private route, the child component renders and after a while the Autheticate function is completed. In the Authenticate function I make a request that returns the token data and saves it in the sessionStorage

Authenticate.js

const Authenticate = async () => {
    let token = localStorage.getItem("token");

    if (token) {
        token = "Bearer " + token;

        let response = await tokenRequest(token);
        if (response) {
            if (response.status === 200) {
                await sessionStorage.setItem(
                    "userData",
                    JSON.stringify(response.data.token)
                );
                return true;
            } else {
                localStorage.clear();
                sessionStorage.clear();
                return false;
            }
        } else {
            return false;
        }
    } else {
        localStorage.clear();

        return false;
    }
};

export default Authenticate;

How could I finish the function's task and then redirect to the child component?

Bruno Santi
  • 192
  • 8

1 Answers1

-1

Within your login route, you can use the history api's state that you are setting in your redirect to navigate back once the user logs in. The state gets stored in the location variable in react router dom. https://reacttraining.com/react-router/web/api/location

Other than that, your Authenticate function currently returns a Promise of a boolean. Promises are always truthy, so your Redirect is likely never being run.

For the logic of how to get the PrivateRoute to work with asynchronous checks, I'll refer you to this which is from a similar issue: authorized route vs unauthorized routes reactjs not properly loading

Zachary Haber
  • 10,376
  • 1
  • 17
  • 31