Created
May 20, 2019 16:41
-
-
Save peksipatongeis/51b07ed61eaa2370a194970750316425 to your computer and use it in GitHub Desktop.
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
function AuthProvider(props) { | |
const [token, setToken] = useLocalStorage('token', ''); | |
return <AuthContext.Provider value={{ token, setToken }} {...props} />; | |
} | |
function useLogin() { | |
const { setToken } = useContext(AuthContext); | |
const login = async ({ username, password }) => { | |
try { | |
const response = await axios({}); | |
setToken(response.data.token); | |
} catch (err) { | |
// ... | |
} | |
}; | |
return { login }; | |
} | |
function useRegistration() { | |
const { setToken } = useContext(AuthContext); | |
const register = async ({ username, email, password }) => { | |
try { | |
const response = await axios({}); | |
setToken(response.data.token); | |
} catch (err) { | |
// ... | |
} | |
}; | |
return { register }; | |
} | |
function useAuthenticatedUser() { | |
const { token, setToken } = useContext(AuthContext); | |
const logout = () => { | |
setToken(''); | |
}; | |
return { isAuthenticated: !!token, logout }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment