Last active
December 7, 2019 01:03
-
-
Save lhas-dev/7f9c485ab371a9b89411bfa04577a697 to your computer and use it in GitHub Desktop.
Context API Sample for Authentication
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, { useReducer, useEffect } from "react"; | |
import { createContext } from "react"; | |
interface AuthData { | |
id: number; | |
email: string; | |
roles: string[]; | |
token: string; | |
} | |
interface AuthState { | |
isAuthenticated: boolean; | |
data: AuthData; | |
} | |
interface AuthProviderProps { | |
children: React.ReactNode; | |
} | |
const AuthContext = createContext({}); | |
const initialState: AuthState = { | |
isAuthenticated: false, | |
data: { | |
id: 0, | |
email: "", | |
roles: [], | |
token: "" | |
} | |
}; | |
const reducer = (state: AuthState, action: any) => { | |
const actions: any = { | |
LOGIN: (payload: AuthData) => { | |
const newState = { | |
...state, | |
isAuthenticated: true, | |
data: payload | |
}; | |
return newState; | |
} | |
}; | |
return actions[action.type](action.payload || null); | |
}; | |
export const AuthProvider = ({ children }: AuthProviderProps) => { | |
const [state, dispatch] = useReducer(reducer, initialState); | |
// didMount | |
useEffect(() => { | |
const localState = window.localStorage.getItem("cookify:auth"); | |
if (!localState) { | |
return; | |
} | |
dispatch({ | |
type: "LOGIN", | |
payload: JSON.parse(localState).data | |
}); | |
}, []); | |
// Watch `state` changes | |
useEffect(() => { | |
if (!state.isAuthenticated) { | |
return; | |
} | |
window.localStorage.setItem("cookify:auth", JSON.stringify(state)); | |
}, [state]); | |
return ( | |
<AuthContext.Provider value={{ state, dispatch }}> | |
{children} | |
</AuthContext.Provider> | |
); | |
}; | |
export const useAuth: any = () => React.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
import React, { useState, useEffect } from "react"; | |
import { RouteComponentProps } from "react-router-dom"; | |
import { useAuth } from "contexts/auth"; | |
interface LoginProps extends RouteComponentProps {} | |
const Login = ({ history }: LoginProps) => { | |
const auth = useAuth(); | |
// Redirect if already authenticated | |
useEffect(() => { | |
if (auth.state.isAuthenticated) { | |
history.push("/home"); | |
} | |
}, [auth.state, history]); | |
const handleFormSubmit = async (data: any) => { | |
setLoading(true); | |
try { | |
const response = await AuthService.login(data.email, data.password); | |
// Dispatch `LOGIN` action with Auth Context API Hook | |
auth.dispatch({ | |
type: "LOGIN", | |
payload: response.data | |
}); | |
} catch (e) { | |
} | |
}; | |
return ( | |
<form /> | |
); | |
}; | |
export default Login; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment