-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApp.js
100 lines (86 loc) · 2.46 KB
/
App.js
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
import React, { useEffect, useState, useMemo } from 'react';
import { StatusBar, ScrollView } from 'react-native'
import { ActivityIndicator, View, Text, Alert } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import LoginStackScreen from './src/Login/LoginStackScreen';
import MainStackScreen from './src/MainStack/MainStackScreen';
import { AuthContext } from './src/components/context';
import { NavigationContainer } from '@react-navigation/native';
export default App = () => {
const initialLoginState = {
isLoading: true,
userToken: null,
userId: null,
socket: null,
username: null,
};
const loginReducer = (prevState, action) => {
switch (action.type) {
case 'RETRIEVE_TOKEN':
return {
...prevState,
userToken: action.token,
isLoading: false,
username: action.username
};
case 'LOGIN':
return {
...prevState,
userToken: action.userToken,
isLoading: false,
};
case 'LOGOUT':
return {
...prevState,
userToken: null,
isLoading: false,
userId: null,
socket: null,
username: null,
};
case 'REGISTER':
return {
...prevState,
userToken: action.token,
isLoading: false,
userId: action.userId,
socket: action.socket,
username: action.username
};
}
}
const [loginState, dispatch] = React.useReducer(loginReducer, initialLoginState);
const authContext = {
loginState,
dispatch,
};
useEffect(() => {
setTimeout(async () => {
let userToken;
userToken = null;
try {
userToken = await AsyncStorage.getItem('userToken');
username = await AsyncStorage.getItem('username');
} catch (e) {
console.log(e);
}
dispatch({ type: 'RETRIEVE_TOKEN', token: userToken , username: username});
}, 1000);
}, []);
if (loginState.isLoading) {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<ActivityIndicator size="large"></ActivityIndicator>
</View>
);
}
return (
<AuthContext.Provider value={authContext}>
<NavigationContainer>
{loginState.userToken != null ?
<MainStackScreen/>
: <LoginStackScreen />}
</ NavigationContainer>
</AuthContext.Provider>
)
}