Skip to content

Instantly share code, notes, and snippets.

@YussufElarif
Last active December 31, 2020 21:42
Show Gist options
  • Save YussufElarif/a8eec8432a1eccfd42b27a262c58e525 to your computer and use it in GitHub Desktop.
Save YussufElarif/a8eec8432a1eccfd42b27a262c58e525 to your computer and use it in GitHub Desktop.
AuthRouteGuard
import React from 'react';
import { useSelector } from 'react-redux';
import { Route, RouteProps, Redirect, useLocation } from 'react-router-dom';
import { useSearchParams } from 'hooks';
import { StatusEnum } from 'reducers/models';
import { Loader } from 'components/elements';
export function AppRoute({ component, secured, ...props }: (RouteProps & { secured?: boolean }))
{
function render(childProps: any)
{
return <Render
{...childProps}
secured={secured}
component={component} />;
}
return <Route
{...props}
render={render} />;
}
function Render({ component, secured, ...childProps }: any)
{
const { user, status } = useSelector(store => store.auth);
const { pathname } = useLocation();
const { redirect } = useSearchParams();
if (status === StatusEnum.Loading)
{
return <Loader />;
}
if (secured)
{
if (!user)
{
if (pathname === '/')
{
return <Redirect to="/login" />;
}
return <Redirect to={`/login?redirect=${pathname}`} />;
}
if (pathname === '/')
{
return <Redirect to="/home" />;
}
if (user.onBoarded && pathname === '/onboard')
{
return <Redirect to="/home" />;
}
if (!user.onBoarded && pathname !== '/onboard')
{
return <Redirect to="/onboard" />;
}
}
if (!secured)
{
if (user)
{
if (redirect)
{
return <Redirect to={redirect} />;
}
return <Redirect to="/home" />;
}
if (pathname === '/')
{
return <Redirect to="/login" />;
}
}
const AppComponent = component;
return <AppComponent {...childProps} />;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment