-
Notifications
You must be signed in to change notification settings - Fork 140
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #536 from VinayLodhi1712/privateroutes
private routes and hospital page added : #468 done
- Loading branch information
Showing
3 changed files
with
147 additions
and
155 deletions.
There are no files selected for viewing
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,21 +1,16 @@ | ||
import { useState, useEffect } from 'react'; | ||
import { Outlet } from 'react-router-dom'; | ||
import { useContext } from 'react'; | ||
import { Outlet, Navigate } from 'react-router-dom'; | ||
import Spinner from './spinner'; | ||
import { UserContext } from '../store/userContext'; // Import the UserContext | ||
|
||
export default function PrivateRoute() { | ||
const [ok, setOk] = useState(false); | ||
useEffect(() => { | ||
const AuthCheck = async () => { | ||
const user = localStorage.getItem('userid'); | ||
const { isAuthenticated, loading } = useContext(UserContext); // Get auth and loading state from context | ||
|
||
if (user) { | ||
setOk(true); | ||
} else { | ||
setOk(false); | ||
} | ||
}; | ||
AuthCheck(); | ||
}, []); | ||
// While checking authentication (loading), show Spinner | ||
if (loading) { | ||
return <Spinner />; | ||
} | ||
|
||
return ok ? <Outlet /> : <Spinner />; | ||
// If authenticated, show the protected route, otherwise redirect to login | ||
return isAuthenticated ? <Outlet /> : <Navigate to="/login" />; | ||
} |
Oops, something went wrong.