Created
August 15, 2021 20:18
-
-
Save rikonor/61af42c4a9fa6cc9fa2cabb841645d52 to your computer and use it in GitHub Desktop.
Context + useReducer
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 { 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