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.
isAuthenticated and role routes
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>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment