Skip to content

Instantly share code, notes, and snippets.

@kp-gists
Created January 16, 2023 08:35
Show Gist options
  • Save kp-gists/c6cb5a1a681919f904b1fd85f90a66e7 to your computer and use it in GitHub Desktop.
Save kp-gists/c6cb5a1a681919f904b1fd85f90a66e7 to your computer and use it in GitHub Desktop.

Revisions

  1. kp-gists created this gist Jan 16, 2023.
    28 changes: 28 additions & 0 deletions routes
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,28 @@
    import { useSelector } from 'react-redux';
    import { useHistory } from 'react-router-dom';

    function PrivateRoute({ children, ...rest }) {
    const isAuthenticated = useSelector((state) => state.auth.isAuthenticated);
    const history = useHistory();

    if (!isAuthenticated) {
    history.push('/login');
    return null;
    }

    return <Route {...rest}>{children}</Route>;

    import { useSelector } from 'react-redux';
    import { useHistory } from 'react-router-dom';

    function AdminRoute({ children, ...rest }) {
    const role = useSelector((state) => state.auth.user.role);
    const history = useHistory();

    if (role !== 'admin') {
    history.push('/');
    return null;
    }

    return <Route {...rest}>{children}</Route>;
    }