-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathApp.js
More file actions
334 lines (304 loc) · 10.5 KB
/
App.js
File metadata and controls
334 lines (304 loc) · 10.5 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
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
globalThis.RNFB_SILENCE_MODULAR_DEPRECATION_WARNINGS = true;
import React, { useCallback, useEffect, useState } from "react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { StyleSheet, View, Text, Linking } from "react-native";
import * as SplashScreen from "expo-splash-screen";
import { SafeAreaProvider } from "react-native-safe-area-context";
import FlashMessage from "react-native-flash-message";
import { StripeProvider } from "@stripe/stripe-react-native";
import * as Notifications from "expo-notifications";
import NetInfo from "@react-native-community/netinfo";
import "./firebase.js";
import Config from "react-native-config";
const STRIPE_PUBLIC_KEY = Config.STRIPE_PUBLIC_KEY || "";
import { Navigation } from "#navigation";
import { localStorage, Context, userSvc } from "#services";
import { NoInternetModal, RequireRegistration } from "#modals";
import { DropdownBackdrop } from "#backdrops";
import { FIVE_MINUTES, isTokenExpired } from "#utils";
import { GestureHandlerRootView } from "react-native-gesture-handler";
Notifications.setNotificationHandler({
handleNotification: async () => ({
shouldShowAlert: true,
shouldPlaySound: false,
shouldSetBadge: false,
}),
});
// Create a react-query client
const queryClient = new QueryClient({
defaultOptions: { queries: { refetchInterval: FIVE_MINUTES } },
});
class AppErrorBoundary extends React.Component {
state = { error: null };
static getDerivedStateFromError(error) {
return { error };
}
componentDidCatch(error, errorInfo) {
if (__DEV__) {
// eslint-disable-next-line no-console
console.error("AppErrorBoundary:", error, errorInfo);
}
}
render() {
if (this.state.error) {
return (
<View style={styles.errorContainer}>
<Text style={styles.errorTitle}>Something went wrong</Text>
<Text style={styles.errorText}>
{this.state.error?.message ?? String(this.state.error)}
</Text>
</View>
);
}
return this.props.children;
}
}
function App() {
const [token, setToken] = useState();
const [initialRouteName, setInitialRouteName] = useState("TabNavigation"); // Initial route name for the AppNavigation
const [initialAuthRouteName, setInitialAuthRouteName] = useState("Welcome"); // Initial route name for the AuthNavigation
const [isTmpUser, setIsTmpUser] = useState(null); // Is the user logged in as a guest
const [isRegistrationModalOpan, setIsRegistrationModalOpen] = useState(false);
const [currencySymbol, setCurrencySymbol] = useState("");
const [userPin, setUserPin] = useState(); // The value of the user's PIN code
const [hasCheckedTmpUser, setHasCheckedTmpUser] = useState(false);
const [activeCoupon, setActiveCoupon] = useState();
const [isAnonymousRegister, setIsAnonymousRegister] = useState(false);
const [theme, setTheme] = useState(null);
const [isInConsultation, setIsInConsultation] = useState(false);
const [isLoginDisabled, setIsLoginDisabled] = useState(false);
const [hasAuthenticatedWithPin, setHasAuthenticatedWithPin] = useState(false);
const [isConnected, setIsConnected] = useState(true);
const [country, setCountry] = useState(null);
const [selectedCountry, setSelectedCountry] = useState(null); // full country object { value, label, countryID, ... }
const [isPodcastsActive, setIsPodcastsActive] = useState(false);
const [isVideosActive, setIsVideosActive] = useState(false);
const [pendingDeepLink, setPendingDeepLink] = useState(null);
const [dropdownOptions, setDropdownOptions] = useState({
isOpen: false,
options: [],
heading: "",
selectedOption: "",
handleChooseOption: () => {},
dropdownId: null,
});
const handleRegistrationModalClose = () => setIsRegistrationModalOpen(false);
const handleRegistrationModalOpen = () => setIsRegistrationModalOpen(true);
const handleRegisterRedirection = () => {
setInitialAuthRouteName("RegisterPreview");
handleRegistrationModalClose();
localStorage.removeItem("token");
localStorage.removeItem("refresh-token");
localStorage.removeItem("expires-in");
setToken(null);
};
// Add network connectivity check
useEffect(() => {
NetInfo.fetch().then((state) => {
setIsConnected(state.isConnected);
});
const unsubscribe = NetInfo.addEventListener((state) => {
setIsConnected(state.isConnected);
});
return () => {
unsubscribe();
};
}, []);
useEffect(() => {
async function checkCurencySymbol() {
const localStorageCurrencySymbol =
await localStorage.getItem("currencySymbol");
if (!currencySymbol && localStorageCurrencySymbol) {
setCurrencySymbol(localStorageCurrencySymbol);
}
if (!localStorageCurrencySymbol && currencySymbol) {
await localStorage.setItem("currencySymbol", currencySymbol);
}
if (
localStorageCurrencySymbol &&
currencySymbol &&
localStorageCurrencySymbol !== currencySymbol
) {
await localStorage.setItem("currencySymbol", currencySymbol);
}
}
async function checkCountry() {
const localStorageCountry = await localStorage.getItem("country");
if (!country && localStorageCountry) {
setCountry(localStorageCountry);
}
}
checkCurencySymbol();
checkCountry();
}, [currencySymbol, country]);
const handleTokenCheck = async (data) => {
const [token, pinCode] = data;
const clearTokenIfNoPinOrBiometrics = async () => {
// If the client doesn't have biometrics enabled and doesn't have a pin code remove the
// token from the local storage, so that re-authentication is required on next app launch
const hasBiometrics = await localStorage.getItem("biometrics-enabled");
// await localStorage.removeItem("has-declined-biometrics");
if (!hasBiometrics && !pinCode && token && !__DEV__) {
await localStorage.removeItem("token");
setToken(null);
}
};
clearTokenIfNoPinOrBiometrics();
};
useEffect(() => {
SplashScreen.preventAutoHideAsync();
async function checkToken() {
const token = await localStorage.getItem("token");
const pinCode = await localStorage.getItem("pin-code");
setUserPin(pinCode);
// Treat expired or invalid token as no token (clear storage and stay logged out)
if (token && isTokenExpired(token)) {
await localStorage.removeItem("token");
await localStorage.removeItem("refresh-token");
await localStorage.removeItem("expires-in");
setToken(null);
return [null, pinCode];
}
setToken(token);
return [token, pinCode];
}
checkToken().then((data) => {
handleTokenCheck(data);
const [tokenFromCheck] = data;
Linking.getInitialURL().then((url) => {
if (url && !tokenFromCheck) {
setPendingDeepLink(url);
// Decide which auth screen to show first:
// - Welcome: no country selected yet
// - Login: country already chosen
localStorage.getItem("country").then((storedCountry) => {
const hasCountry = !!storedCountry;
setInitialAuthRouteName(hasCountry ? "Login" : "Welcome");
});
}
});
});
}, []);
useEffect(() => {
async function checkIsTmpUser() {
if (token) {
const userId = await userSvc.getUserID();
const tmpUser = userId === "tmp-user";
setIsTmpUser(tmpUser);
setHasCheckedTmpUser(true);
}
}
checkIsTmpUser();
}, [token]);
// Hide the splash screen once the root view is laid out
const onLayoutRootView = useCallback(async () => {
await SplashScreen.hideAsync();
}, []);
// if (error) {
// return (
// <View style={styles.container}>{JSON.stringify(error, null, 2)}</View>
// );
// }
const contextValues = {
token,
setToken,
userPin,
initialRouteName,
setInitialRouteName,
isTmpUser,
setIsTmpUser,
handleRegistrationModalOpen,
initialAuthRouteName,
setInitialAuthRouteName,
currencySymbol,
setCurrencySymbol,
dropdownOptions,
setDropdownOptions,
hasCheckedTmpUser,
activeCoupon,
setActiveCoupon,
isAnonymousRegister,
setIsAnonymousRegister,
theme,
setTheme,
isLoginDisabled,
setIsLoginDisabled,
isInConsultation,
setIsInConsultation,
setUserPin,
hasAuthenticatedWithPin,
setHasAuthenticatedWithPin,
country,
setCountry,
selectedCountry,
setSelectedCountry,
isPodcastsActive,
setIsPodcastsActive,
isVideosActive,
setIsVideosActive,
pendingDeepLink,
setPendingDeepLink,
};
return (
<AppErrorBoundary>
<GestureHandlerRootView style={styles.flex1}>
<StripeProvider publishableKey={STRIPE_PUBLIC_KEY}>
<Context.Provider value={contextValues}>
<QueryClientProvider client={queryClient}>
<SafeAreaProvider>
<View style={styles.flex1} onLayout={onLayoutRootView}>
<Navigation
contextTheme={theme}
setTheme={setTheme}
isInConsultation={isInConsultation}
>
<NoInternetModal theme={theme} isVisible={!isConnected} />
<DropdownBackdrop
onClose={() =>
setDropdownOptions((options) => ({
...options,
isOpen: false,
}))
}
{...dropdownOptions}
/>
<RequireRegistration
handleContinue={handleRegisterRedirection}
isOpen={isRegistrationModalOpan}
onClose={handleRegistrationModalClose}
/>
</Navigation>
</View>
</SafeAreaProvider>
<FlashMessage position="top" />
</QueryClientProvider>
</Context.Provider>
</StripeProvider>
</GestureHandlerRootView>
</AppErrorBoundary>
);
}
export default App;
const styles = StyleSheet.create({
container: {
backgroundColor: "#fff",
flex: 1,
},
flex1: { flex: 1 },
errorContainer: {
flex: 1,
justifyContent: "center",
padding: 24,
backgroundColor: "#1a1a1a",
},
errorTitle: {
color: "#fff",
fontSize: 18,
fontWeight: "600",
marginBottom: 12,
},
errorText: {
color: "#f44",
fontSize: 14,
},
});