Skip to content

Instantly share code, notes, and snippets.

@pubudu-ranasinghe
Created November 3, 2019 12:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pubudu-ranasinghe/b3c4a6a33c7e2b663b51d51144899362 to your computer and use it in GitHub Desktop.
Save pubudu-ranasinghe/b3c4a6a33c7e2b663b51d51144899362 to your computer and use it in GitHub Desktop.
react-context-example-17
import React, { createContext, useReducer, useContext } from "react";
export const AuthContext = createContext();
// Initial state
const initialState = {
isLoggedIn: false,
name: null,
error: null
};
// Actions
export const LOGIN_SUCCESS = "LOGIN_SUCCESS";
export const LOGIN_FAIL = "LOGIN_FAIL";
export const LOGOUT = "LOGOUT";
// Action creators
export function loginSuccess(name) {
return { type: LOGIN_SUCCESS, name };
}
export function loginFail(error) {
return { type: LOGIN_FAIL, error };
}
export function logout() {
return { type: LOGOUT };
}
// Reducer
export function authReducer(state, action) {
switch (action.type) {
case LOGIN_SUCCESS:
return { isLoggedIn: true, name: action.name, error: null };
case LOGIN_FAIL:
return { isLoggedIn: false, name: null, error: action.error };
case LOGOUT:
return { isLoggedIn: false };
default:
return state;
}
}
function AuthProvider(props) {
const [auth, dispatch] = useReducer(authReducer, initialState);
const authData = { auth, dispatch };
return <AuthContext.Provider value={authData} {...props} />;
}
function useAuthContext() {
return useContext(AuthContext);
}
export { AuthProvider, useAuthContext };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment