Created
July 13, 2020 10:00
-
-
Save mtreacy002/fe04afa7188fff6ba0d4b96f25458367 to your computer and use it in GitHub Desktop.
Protected pagee with Reactjs
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
import React, {createContext, useEffect, useState} from "react"; | |
import Cookies from "js-cookie"; | |
export const AuthContext = createContext({ | |
user: null, isAuth: false, login: () => { | |
}, logout: () => { | |
} | |
}); | |
function AuthProvider({ children }) { | |
const [isAuth, setIsAuth] = useState(false); | |
const [user, setUser] = useState(null); | |
useEffect( | |
() => { | |
const userCookie = Cookies.get('user'); | |
if(userCookie){ | |
setIsAuth(true); | |
return; | |
} | |
setIsAuth(false); | |
}, | |
[user] | |
); | |
const login = (token, user) => { | |
if(user) { | |
Cookies.set("user", user); | |
Cookies.set("access_token", token["access_token"]); | |
Cookies.set("access_expiry", token["access_expiry"]); | |
setUser(user); | |
} | |
}; | |
const logout = () => { | |
Cookies.remove("user"); | |
Cookies.remove("access_token"); | |
Cookies.remove("access_expiry"); | |
setUser(null); | |
}; | |
return ( | |
<AuthContext.Provider | |
value={{ | |
user: Cookies.get("user"), | |
isAuth: isAuth, | |
login: login, | |
logout: logout | |
}} | |
> | |
{children} | |
</AuthContext.Provider> | |
); | |
} | |
export default AuthProvider; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment