-
Notifications
You must be signed in to change notification settings - Fork 97
/
Navigator.tsx
executable file
·84 lines (71 loc) · 2.41 KB
/
Navigator.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
import { useState, useEffect } from 'react';
import { View } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import * as SplashScreen from 'expo-splash-screen';
import { useAppSlice, useAppService, IUser } from '@/modules/app';
import BottomSheet from '@/components/BottomSheet';
import { WelcomeBottomSheetContents } from '@/layouts/BottomSheetContents';
import DrawerNavigator from './drawer';
import { loadImages, loadFonts } from '@/theme';
import { useDataPersist, DataPersistKeys } from '@/hooks';
import { isWeb } from '@/utils/deviceInfo';
// keep the splash screen visible while complete fetching resources
SplashScreen.preventAutoHideAsync();
function Navigator() {
const { getUser } = useAppService();
const { dispatch, checked, loggedIn, setUser, setLoggedIn } = useAppSlice();
const { setPersistData, getPersistData } = useDataPersist();
const [isOpen, setOpen] = useState(true);
/**
* preload assets and user data
*/
const preload = async () => {
try {
// preload assets
await Promise.all([loadImages(), loadFonts()]);
// fetch user data (fake promise function to simulate async function)
const user = await getUser();
// store user data to redux
dispatch(setUser(user));
dispatch(setLoggedIn(!!user));
// store user data to persistent storage (async storage)
if (user) setPersistData<IUser>(DataPersistKeys.USER, user);
// hide splash screen
SplashScreen.hideAsync();
} catch (err) {
console.log('[##] preload error:', err);
// if preload failed, try to get user data from persistent storage
getPersistData<IUser>(DataPersistKeys.USER)
.then(user => {
if (user) {
dispatch(setUser(user));
dispatch(setLoggedIn(!!user));
}
})
.finally(() => {
// hide splash screen
SplashScreen.hideAsync();
});
}
};
useEffect(() => {
preload();
}, []);
// TODO: switch router by loggedIn status
console.log('[##] loggedIn', loggedIn);
return checked && loggedIn ? (
<>
<NavigationContainer>
<DrawerNavigator />
</NavigationContainer>
{!isWeb && (
<BottomSheet isOpen={isOpen} initialOpen>
<WelcomeBottomSheetContents onClose={() => setOpen(false)} />
</BottomSheet>
)}
</>
) : (
<View />
);
}
export default Navigator;