-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.js
More file actions
75 lines (66 loc) · 1.66 KB
/
auth.js
File metadata and controls
75 lines (66 loc) · 1.66 KB
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
import React, {createContext, useContext, useReducer, useMemo} from 'react';
import AsyncStorage from '@react-native-community/async-storage';
const AuthContext = createContext();
function reducer(prevState, action) {
switch (action.type) {
case 'RESTORE_TOKEN':
return {
...prevState,
userToken: action.token,
isLoading: false,
};
case 'SIGN_IN':
return {
...prevState,
isSignout: false,
userToken: action.token,
};
case 'SIGN_OUT':
return {
...prevState,
isSignout: true,
userToken: null,
};
}
}
function AuthProvider({children}) {
const [state, dispatch] = useReducer(reducer, {
isLoading: true,
isSignout: false,
userToken: null,
});
const authContext = useMemo(
() => ({
handleSignIn: async (data) => {
dispatch({type: 'SIGN_IN', token: 'dummy-auth-token'});
},
handleSignOut: async () => {
await AsyncStorage.clear();
dispatch({type: 'SIGN_OUT'});
},
bootstrapAsync: async () => {
let userToken;
try {
userToken = await AsyncStorage.getItem('userToken');
} catch (e) {
// Restoring token failed
}
dispatch({type: 'RESTORE_TOKEN', token: userToken});
},
}),
[],
);
return (
<AuthContext.Provider value={{state, authContext}}>
{children}
</AuthContext.Provider>
);
}
function useAuth() {
const context = useContext(AuthContext);
if (typeof context === undefined) {
throw new Error('useAuth must be used within a provider');
}
return context;
}
export {AuthProvider, useAuth};