Skip to content

Instantly share code, notes, and snippets.

@rikonor
Created August 15, 2021 20:18
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 rikonor/61af42c4a9fa6cc9fa2cabb841645d52 to your computer and use it in GitHub Desktop.
Save rikonor/61af42c4a9fa6cc9fa2cabb841645d52 to your computer and use it in GitHub Desktop.
Context + useReducer
import { createContext, useContext, useReducer } from "react";
const initialState = {
isSigningIn: false,
isSignedIn: false,
};
const AuthContext = createContext(initialState);
const reducer = (state, action) => {
switch (action.type) {
case "SIGNING_IN":
return { ...state, isSigningIn: true };
case "SIGNED_IN":
return { ...state, isSigningIn: false, isSignedIn: true };
case "SIGNED_OUT":
return { ...state, isSignedIn: false };
default:
throw new Error();
}
};
export const AuthProvider = (props) => {
const [state, dispatch] = useReducer(reducer, initialState);
const signIn = () => {
const { isSignedIn, isSigningIn } = state;
if (!!isSignedIn || !!isSigningIn) return;
dispatch({ type: "SIGNING_IN" });
// await
dispatch({ type: "SIGNED_IN" });
};
const signOut = () => {
const { isSignedIn } = state;
if (!isSignedIn) return;
// await
dispatch({ type: "SIGNED_OUT" });
};
return (
<AuthContext.Provider
value={{
...state,
signIn,
signOut,
}}
{...props}
/>
);
};
export const useAuth = () => useContext(AuthContext);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment