I want to protect a route by checking
a. user is authenticated. If the user is not authenticated then redirect them to the login page
b. user has a cart. If no cart, then redirect them back to cart page to add items.
For an example , if a user wants to access the checkout page. The user must be first loggedIn and then the user must have items added to his cart.
Now the guards , I would like to separate it two different components
a. to check if user is logged - NewAuthenticatedRoute.jsx
b. to check if user has a cart - CheckoutRoute.jsx
//NewAuthenticatedRoute.jsx
import React from "react";
import { Route, Redirect } from "react-router-dom";
import useAuthenticated from "../../hooks/useAuthenticated";
const NewAuthenticatedRoute = ({ children, ...rest }) => {
const { isAuthenticated } = useAuthenticated();
return (
<Route
{...rest}
render={({ location }) => {
return isAuthenticated ? (
children
) : (
<Redirect
to={{
pathname: "/login",
state: { from: location },
}}
/>
);
}}
/>
);
};
//CheckoutRoute.jsx
import React from "react";
import { Route, Redirect } from "react-router-dom";
import useCart from "../../hooks/useCart";
const CheckoutRoute = ({ children, ...rest }) => {
const { isCartEmpty } = useCart();
return (
<Route
{...rest}
render={({ location }) => {
return !isCartEmpty ? (
children
) : (
<Redirect
to={{
pathname: "/cart",
state: { from: location },
}}
/>
);
}}
/>
);
};
This works but any route after I add after that, does not work
//App.jsx
const App = () => {
return (
<Router>
<Switch>
{/* Nesting routes */}
<NewAuthenticatedRoute>
<CheckoutRoute exact path="/checkout">
<Checkout></Checkout>
</CheckoutRoute>
<CheckoutRoute exact path="/payment">
<StripePayment></StripePayment>
</CheckoutRoute>
</NewAuthenticatedRoute> //THESE ROUTES ARE WORKING PERFECTLY
<Route path="*">
<NotFound></NotFound>
</Route> // THIS ROUTE IS NOT WORKING AND DOES NOT CATCH 404
</Switch>
</Router>
);
};
I am using React Router DOM v5.
Please help
thank you