-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApp.tsx
257 lines (246 loc) · 7.13 KB
/
App.tsx
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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
/**
* Sample React Native App
* https://github.com/facebook/react-native
*
* @format
* @flow strict-local
*/
import 'react-native-gesture-handler';
import React, {useEffect, createContext, useMemo, Reducer} from 'react';
import {NavigationContainer} from '@react-navigation/native';
import {createStackNavigator} from '@react-navigation/stack';
// import { Provider } from 'react-redux';
// import { createStore, applyMiddleware, StoreEnhancer } from 'redux';
import LogIn from './app/screens/login';
import BookList from './app/screens/bookList';
import BookDescription from './app/screens/bookDescription';
import ARScreen from './app/screens/arScreen';
import AsyncStorage from '@react-native-community/async-storage';
import constants from './app/utils/constant';
import {authenticate, getBookList} from './app/services/book.service';
import SplashScreen from './app/screens/splashScreen';
// type AuthContextType = {
// signIn: any;
// signOut: any;
// }
export const AuthContext = createContext<any>(null);
export type StackParamList = {
Home: undefined;
BookList: undefined;
BookPhraseDetails: {
book: any;
};
ARScreen: {
book: any;
bookDescription: any;
};
};
const Stack = createStackNavigator<StackParamList>();
type State = {
isLoading: boolean;
isSignout: boolean;
userToken: string | null;
books: Array<any>;
};
type Action = {
type: string;
token?: string;
books?: Array<any>;
};
const App = () => {
const [state, dispatch] = React.useReducer<Reducer<State, Action>>(
(prevState: State, action: Action) => {
switch (action.type) {
case constants.RESTORE_TOKEN:
return {
...prevState,
userToken: action.token,
isLoading: false,
};
case constants.SIGN_IN:
return {
...prevState,
isSignout: false,
userToken: action.token,
};
case constants.SIGN_OUT:
return {
...prevState,
isSignout: true,
userToken: null,
books: [],
};
case constants.SET_BOOKS:
return {
...prevState,
books: action.books,
};
}
},
{
isLoading: true,
isSignout: false,
userToken: null,
books: [],
},
);
useEffect(() => {
// Fetch the token from storage then navigate to our appropriate place
const bootstrapAsync = async () => {
let userToken;
let bookList;
try {
userToken = await AsyncStorage.getItem(constants.USER_TOKEN);
} catch (e) {
// Restoring token failed
userToken = null;
}
// After restoring token, we may need to validate it in production apps
// This will switch to the App screen or Auth screen and this loading
// screen will be unmounted and thrown away.
dispatch({type: constants.RESTORE_TOKEN, token: userToken});
try {
bookList = await AsyncStorage.getItem(constants.BOOK_LIST);
} catch (e) {
// Restoring token failed
bookList = [];
}
if (!bookList) {
bookList = [];
}
dispatch({type: constants.SET_BOOKS, books: bookList});
};
bootstrapAsync();
}, []);
const {userToken, books} = state;
const authContext = useMemo(
() => ({
signIn: async (username: string, password: string, callback?: any) => {
// In a production app, we need to send some data (usually username, password) to server and get a token
// We will also need to handle errors if sign in failed
// After getting token, we need to persist the token using `SecureStore`
// In the example, we'll use a dummy token
authenticate({username, password})
.then(async response => {
const responseStatus = response[0];
const responseJSON = response[1];
if (responseStatus === 200) {
await AsyncStorage.setItem(
constants.USER_TOKEN,
responseJSON.token,
);
dispatch({type: constants.SIGN_IN, token: responseJSON.token});
} else {
console.log('error', responseJSON);
}
})
.catch(_err => {
console.log('error', _err);
})
.then(() => {
if (callback) {
callback();
}
});
},
signOut: () => dispatch({type: constants.SIGN_OUT}),
getToken: () => userToken,
loadBooksList: async (callback?: any) => {
getBookList({userToken})
.then(async response => {
const responseStatus = response[0];
const responseJSON = response[1];
if (responseStatus === 200) {
await AsyncStorage.setItem(
constants.BOOK_LIST,
JSON.stringify(responseJSON.results),
);
dispatch({
type: constants.SET_BOOKS,
books: [...responseJSON.results],
});
} else {
console.log('error', responseJSON);
}
})
.catch(_err => {
console.log('error', _err);
})
.then(() => {
if (callback) {
callback();
}
});
},
getBooks: () => {
return books;
},
}),
[userToken, books],
);
if (state.isLoading) {
// We haven't finished checking for the token yet
return <SplashScreen />;
}
return (
<AuthContext.Provider value={authContext}>
<NavigationContainer>
<Stack.Navigator
screenOptions={{
headerStyle: {
backgroundColor: constants.DARK_COLOR,
},
headerTintColor: constants.WHITE,
headerTitleStyle: {
fontWeight: 'bold',
},
}}>
{state.userToken == null ? (
<>
<Stack.Screen
name="Home"
component={LogIn}
options={{
headerShown: false,
animationTypeForReplace: state.isSignout ? 'pop' : 'push',
}}
/>
</>
) : (
<>
<Stack.Screen
name="BookList"
options={{
title: 'Books List',
}}
component={BookList}
/>
<Stack.Screen
name="BookPhraseDetails"
component={BookDescription}
initialParams={{
book: {},
}}
options={{
title: 'Books Details',
}}
/>
<Stack.Screen
name="ARScreen"
component={ARScreen}
initialParams={{
book: {},
bookDescription: {},
}}
options={{
headerShown: false,
}}
/>
</>
)}
</Stack.Navigator>
</NavigationContainer>
</AuthContext.Provider>
);
};
export default App;