0

I would like to do the following

a. Check if user is authenticated

b. Check if the user has a cart

If the following situations are satisfied , I should be able to access these two routes

a. /payment

b. /checkout

The following works

const App = () => {
  return (
    <Router>
      <Switch>
        {/* Nesting routes  */}
        <NewAuthenticatedRoute>
          <CheckoutRoute exact path="/checkout">
            <Checkout></Checkout>
          </CheckoutRoute>
          <CheckoutRoute exact path="/payment">
            <StripePayment></StripePayment>
          </CheckoutRoute>
        </NewAuthenticatedRoute>
        <Route path="*">
          <NotFound></NotFound>
        </Route>
      </Switch>
    </Router>
  );
};

Basically from the above code.

  1. NewAuthenticatedRoute is responsible to check if user is authenticated.
  2. Checkout Route is responsible to check if user has a cart.

This works but it is unable to catch all routes , basically the code below does not work.

 <Route path="*">
              <NotFound></NotFound>
            </Route>

If I comment out NewAuthenticatedRoute section, the Not Found Route works

//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 },
            }}
          />
        );
      }}
    />
  );
};

To reiterate, basically the NewAuthenticatedRoute & CheckoutRoute acts as guards/middleware for a user to access the checkout and payment route.

Right now the guards work as expected, however the route below them is not working.

<Route path="*">
          <NotFound></NotFound>
        </Route>

I am using React router dom v5.2

Please advise

Thank you

desh
  • 627
  • 1
  • 7
  • 19

0 Answers0