Skip to content

Instantly share code, notes, and snippets.

@peksipatongeis
Created May 20, 2019 16:41
Show Gist options
  • Save peksipatongeis/51b07ed61eaa2370a194970750316425 to your computer and use it in GitHub Desktop.
Save peksipatongeis/51b07ed61eaa2370a194970750316425 to your computer and use it in GitHub Desktop.
AuthContext
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