Last active
March 22, 2023 21:32
-
-
Save KirillTregubov/c5491a28022dba813495481b6f4f005b to your computer and use it in GitHub Desktop.
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' | |
type State = { | |
isLoading: boolean | |
isSignout: boolean | |
userToken: string | null | |
} | |
type Action = | |
| { type: 'LOADED' } | |
| { type: 'SIGN_IN'; token: string } | |
| { type: 'SIGN_OUT' } | |
export const AuthContext = createContext({ | |
authState: {} as State, | |
loaded: () => {}, | |
signIn: (token: string) => {}, | |
signOut: () => {} | |
}) | |
export const AuthProvider = ({ children }: any) => { | |
const [authState, dispatch] = useReducer( | |
(prevState: State, action: Action) => { | |
switch (action.type) { | |
case 'LOADED': | |
return { | |
...prevState, | |
isLoading: false | |
} | |
case 'SIGN_IN': | |
return { | |
...prevState, | |
isLoading: false, | |
isSignout: false, | |
userToken: action.token | |
} | |
case 'SIGN_OUT': | |
return { | |
...prevState, | |
isSignout: true, | |
userToken: null | |
} | |
} | |
}, | |
{ | |
isLoading: true, | |
isSignout: false, | |
userToken: null | |
} | |
) | |
return ( | |
<AuthContext.Provider | |
value={{ | |
authState, | |
loaded: () => { | |
dispatch({ type: 'LOADED' }) | |
}, | |
signIn: (token: string) => { | |
dispatch({ type: 'SIGN_IN', token }) | |
}, | |
signOut: () => dispatch({ type: 'SIGN_OUT' }) | |
}}> | |
{children} | |
</AuthContext.Provider> | |
) | |
} | |
export default function useAuth() { | |
return useContext(AuthContext) | |
} | |
// USAGE EXAMPLES | |
// Wrap your App.tsx or main entrypoint in <AuthProvider></AuthProvider> | |
// const { signIn } = useAuth() | |
// const { authState } = useAuth() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment