-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[FEAT]: created auth provider and private router
- Loading branch information
1 parent
9caeae4
commit 769fb81
Showing
3 changed files
with
72 additions
and
4 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
import React, { useEffect } from "react"; | ||
import { createContext, useContext, useState } from "react"; | ||
|
||
const AuthContext = createContext(); | ||
|
||
export const AuthProvider = ({ children }) => { | ||
const [userDB, setUserDB] = useState( | ||
JSON.parse(localStorage.getItem("usersInfo")) || [] | ||
); | ||
|
||
const [authenticated, setAuthenticated] = useState( | ||
JSON.parse(localStorage.getItem("authenticated")) || false | ||
); | ||
|
||
useEffect(() => { | ||
localStorage.setItem("usersInfo", JSON.stringify(userDB)); | ||
}, [userDB]); | ||
|
||
useEffect(() => { | ||
localStorage.setItem("authenticated", JSON.stringify(authenticated)); | ||
}, [authenticated]); | ||
|
||
return ( | ||
<AuthContext.Provider | ||
value={{ userDB, setUserDB, authenticated, setAuthenticated }} | ||
> | ||
{children} | ||
</AuthContext.Provider> | ||
); | ||
}; | ||
|
||
export const useAuth = () => useContext(AuthContext); |
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 |
---|---|---|
@@ -0,0 +1,17 @@ | ||
import { Navigate, useLocation } from "react-router-dom"; | ||
|
||
import React from "react"; | ||
|
||
const PrivateRouter = ({ children }) => { | ||
const authenticated = localStorage.getItem("authenticated"); | ||
|
||
let location = useLocation(); | ||
|
||
return authenticated ? ( | ||
children | ||
) : ( | ||
<Navigate to="/" state={{ from: location }} replace /> | ||
); | ||
}; | ||
|
||
export default PrivateRouter; |
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