1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
|
import React, { createContext, ReactNode, useReducer, useEffect, useContext, useMemo, } from 'react'; import AsyncStorage from '@react-native-async-storage/async-storage';
type UserInfo = { username: string; };
type AuthState = { isLoading: boolean; token?: string; userInfo?: UserInfo; };
type AuthAction = { type: 'retrieveToken' | 'login' | 'logout'; token?: string; userInfo?: UserInfo; };
function reducer(state: AuthState, action: AuthAction) { switch (action.type) { case 'retrieveToken': return { ...state, isLoading: false, token: action.token, userInfo: action.userInfo, }; case 'login': return { ...state, isLoading: false, token: action.token, userInfo: action.userInfo, }; case 'logout': return { ...state, isLoading: false, token: undefined, userInfo: undefined, }; } }
const initialState = { isLoading: true, token: undefined, userInfo: undefined, };
const AuthContext = createContext< | { state: AuthState; dispatch: React.Dispatch<AuthAction>; } | undefined >(undefined);
const AuthProvider = ({children}: {children: ReactNode}): JSX.Element => { const [state, dispatch] = useReducer(reducer, initialState);
useEffect(() => { async function retrieveToken() { try { const values = await AsyncStorage.multiGet(['token', 'userInfo']); if (values[0][1] && values[1][1]) { const tokenValue = values[0][1]; const userInfoValue = JSON.parse(values[1][1]); dispatch({ type: 'retrieveToken', token: tokenValue, userInfo: userInfoValue, }); } else { dispatch({ type: 'retrieveToken', token: undefined, userInfo: undefined, }); } } catch { dispatch({ type: 'retrieveToken', token: undefined, userInfo: undefined, }); } } retrieveToken(); }, []);
return ( <AuthContext.Provider value={{state, dispatch}}> {children} </AuthContext.Provider> ); };
const useAuth = (): { state: AuthState; actions: { login: (token: string, userInfo: UserInfo) => Promise<void>; logout: () => Promise<void>; }; } => { const context = useContext(AuthContext); if (!context) { throw new Error('useAuth must be used in AuthProvider!'); }
const authActions = useMemo( () => ({ login: async (token: string, userInfo: UserInfo) => { await AsyncStorage.multiSet([ ['token', token], ['userInfo', JSON.stringify(userInfo)], ]); context.dispatch({type: 'login', token: token, userInfo: userInfo}); }, logout: async () => { await AsyncStorage.multiRemove(['token', 'userInfo']); context.dispatch({ type: 'logout', token: undefined, userInfo: undefined, }); }, }), [context], );
return {state: context.state, actions: authActions}; };
export {AuthProvider, useAuth};
|