Created
January 16, 2023 08:35
-
-
Save kp-gists/c6cb5a1a681919f904b1fd85f90a66e7 to your computer and use it in GitHub Desktop.
isAuthenticated and role routes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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