Created
April 21, 2021 20:51
-
-
Save dimitrisnl/198952d2eded6cc4cbd0432f7d774135 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 {AxiosInstance, AxiosRequestConfig} from 'axios'; | |
| import { | |
| createContext, | |
| FC, | |
| useCallback, | |
| useContext, | |
| useMemo, | |
| useState, | |
| } from 'react'; | |
| import {queryCache} from 'react-query'; | |
| import createClient from '../utils/apiClient'; | |
| import {getAccessToken} from '../utils/authService'; | |
| import {getToken, removeToken, setToken} from '../utils/jwtTokenUtils'; | |
| interface User { | |
| token?: string; | |
| } | |
| type AuthContextProps = { | |
| user: User; | |
| signIn: (token) => void; | |
| signOut: () => void; | |
| } | |
| const AuthContext = createContext({} as IAuthContext); | |
| const AuthProvider: FC = (props) => { | |
| const [user, setUser] = useState<IUser>(() => { | |
| const token = getToken(); | |
| return {token}; | |
| }); | |
| const signIn = useCallback(async () => { | |
| // implement this | |
| }, [setUser]); | |
| const signOut = useCallback(() => { | |
| queryCache.clear(); | |
| removeToken(); | |
| setUser({}); | |
| }, [setUser]); | |
| const value = useMemo(() => ({user, signIn, signOut}), [ | |
| signIn, | |
| signOut, | |
| user, | |
| ]); | |
| return <AuthContext.Provider value={value} {...props} />; | |
| }; | |
| const useAuth = (): AuthContextProps => { | |
| const context = useContext(AuthContext); | |
| return context; | |
| }; | |
| const useClient = (): AxiosInstance => { | |
| const {user, signOut} = useAuth(); | |
| const token = user?.token; | |
| const client = useMemo( | |
| () => createClient({authToken: token, onUnauthorized: signOut}), | |
| [token] | |
| ); | |
| return useCallback((config: AxiosRequestConfig) => client(config), []); | |
| }; | |
| export {AuthProvider, useAuth, useClient}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment