Skip to content Skip to sidebar Skip to footer

Authorized Route Vs Unauthorized Routes Reactjs Not Properly Loading

I am having trouble understanding why my Authorized vs Unauthorized routes are not acting properly.. Here are the way my routes are set up: class App extends Component { render(

Solution 1:

isAuthenticated() is asynchronous and currently returns void. You'll have to make isAuthenticated return a Promise of a boolean.

Once you have isAuthenticated returning a value, you'll need to use an effect and state to pull the actual value out of the promise.

importReact, { useState, useEffect } from'react';
import { Redirect, Route } from'react-router-dom';
import { Api } from'./api';

const isAuthenticated = async () => {
  try {
    const response = awaitApi.isActiveToken(sessionStorage.getItem('token'));
    return response.ok;
  } catch (error) {
    returnfalse;
  }
};

constAuthenticatedRoute = ({ component: Component, ...rest }) => {
  const [authenticated, setAuthenticated] = useState(null);
  useEffect(() => {
    isAuthenticated().then((bool) =>setAuthenticated(bool));
  }, []);

  return (
    <Route
      {...rest}
      render={(props) => {
        if (authenticated === null) return '...loading';
        return authenticated ? <Component {...props} /> : <Redirectto="/login" />;
      }}
    />
  );
};

constUnauthenticatedRoute = ({ component: Component, ...rest }) => {
  const [authenticated, setAuthenticated] = useState(null);
  useEffect(() => {
    isAuthenticated().then((bool) =>setAuthenticated(bool));
  }, []);
  return (
    <Route
      {...rest}
      render={(props) => {
        if (authenticated === null) return '...loading';
        return !authenticated ? <Component {...props} /> : <Redirectto="/" />;
      }}
    />
  );
};

export { AuthenticatedRoute, UnauthenticatedRoute };

Solution 2:

I think the problem is that the Switch component expects certain types of child components, and you're passing it a different component type AuthenticatedRoute which it probably can't handle. Rather than making a new component type, you can convert your components to render functions that just return the Route element so that the Switch only contains routes.

constrenderAuthenticatedRoute = ({ component: Component, ...rest }) => (
  <Route {...rest} render={(props) => (
    isAuthenticated()
      ? <Component {...props} />
      : <Redirectto='/login' />
  )} />
);

constrenderUnauthenticatedRoute = ({ component: Component, ...rest }) => (
  <Route {...rest} render={(props) => (
    !isAuthenticated()
      ? <Component {...props} />
      : <Redirectto='/' />
  )} />
);

classAppextendsComponent {
  render() {
    return (
      <HashRouter><React.Suspensefallback={loading()}><Switch>
              { 
                renderUnauthenticatedRoute({ 
                  exact: true, 
                  path: "/login", 
                  name: "Login Page",
                  component: Login
                })
              }
              <Routeexactpath="/register"name="Register Page"component={Register} /><Routeexactpath="/404"name="Page 404"component={Page404} /><Routeexactpath="/500"name="Page 500"component={Page500} />
              { 
                renderAuthenticatedRoute({
                  path: "/",
                  name: "Home",
                  component: DefaultLayout
                }) 
              }
            </Switch></React.Suspense></HashRouter>
    );
  }
}

Post a Comment for "Authorized Route Vs Unauthorized Routes Reactjs Not Properly Loading"