· 4 years ago · Feb 10, 2021, 08:48 AM
1import React, { useEffect, useState } from 'react';
2import AppLoading from 'expo-app-loading';
3import * as Font from 'expo-font';
4import { AsyncStorage, Alert, SafeAreaView, ActivityIndicator } from 'react-native';
5import 'react-native-gesture-handler';
6import { NavigationContainer } from '@react-navigation/native';
7import { createStackNavigator } from '@react-navigation/stack';
8import {SplashScreen, InScreen, SignInScreen, FullScreenLoader} from './screens';
9import {AuthContext} from './screens/utils';
10
11const getFonts = () => Font.loadAsync({
12 'nunito-light': require('./fonts/Nunito-Light.ttf'),
13 'nunito-regular': require('./fonts/Nunito-Regular.ttf'),
14 'nunito-bold': require('./fonts/Nunito-Bold.ttf'),
15})
16
17const Stack = createStackNavigator();
18
19//export default function App({ navigation }) {
20export default App = () => {
21
22 const [fontsLoaded, setFontsLoaded] = useState(false);
23
24 const [state, dispatch] = React.useReducer(
25 (prevState, action) => {
26 switch (action.type) {
27 case 'RESTORE_TOKEN':
28 return {
29 ...prevState,
30 userToken: action.token,
31 isLoading: false,
32 };
33 case 'SIGN_IN':
34 if(action.token){
35 AsyncStorage.setItem('userToken', action.token);
36 }
37 return {
38 ...prevState,
39 isSignout: false,
40 userToken: action.token,
41 };
42 case 'SIGN_OUT':
43 AsyncStorage.removeItem('userToken');
44 return {
45 ...prevState,
46 isSignout: true,
47 userToken: null,
48 };
49 }
50 },
51 {
52 isLoading: true,
53 isSignout: false,
54 userToken: null,
55 }
56 );
57
58 React.useEffect(() => {
59 // Fetch the token from storage then navigate to our appropriate place
60 const bootstrapAsync = async () => {
61 let userToken;
62
63 try {
64 userToken = await AsyncStorage.getItem('userToken');
65 } catch (e) {
66 // Restoring token failed
67 }
68
69 // After restoring token, we may need to validate it in production apps
70
71 // This will switch to the App screen or Auth screen and this loading
72 // screen will be unmounted and thrown away.
73 dispatch({ type: 'RESTORE_TOKEN', token: userToken });
74 };
75
76 bootstrapAsync();
77 }, []);
78
79 const authContext = React.useMemo(
80 () => ({
81 signIn: async data => {
82 // In a production app, we need to send some data (usually username, password) to server and get a token
83 // We will also need to handle errors if sign in failed
84 // After getting token, we need to persist the token using `AsyncStorage`
85 // In the example, we'll use a dummy token
86
87 //setLoading(true);
88 state.isLoading = true;
89 //navigation.navigate('Splash', { Email: data['email'] });
90 //navigation.navigate('Splash');
91
92 /*
93 if(state.isLoading == true){
94 console.log(state.isLoading);
95 return(
96 <SafeAreaView style={{flex:1,justifyContent:'center',alignItems:'center'}}>
97 <ActivityIndicator size="large"/>
98 </SafeAreaView>
99 )
100 }*/
101 console.log("Email: ", data['email']);
102 console.log("Password: ", data['password']);
103
104 secretKey = '***************************';
105
106 useEffect(() => {
107 fetch('https://website.it/wp-content/themes/theme/app/login.php?key=' + secretKey, {
108 method: 'POST',
109 headers: {
110 'Accept': 'application/json',
111 'Content-Type': 'application/json',
112 },
113 body: JSON.stringify({
114
115 email: data['email'],
116
117 password: data['password'],
118
119 })
120 }).then((response) => response.json()).then((responseJson) => {
121 // If server response message same as Data Matched
122 if(responseJson === 'Data Matched'){
123 //Then open Profile activity and send user email to profile activity.
124 //navigation.navigate('Home', { Email: email });
125 state.isLoading = false;
126 dispatch({ type: 'SIGN_IN', token: 'dummy-auth-token' });
127 }else{
128 state.isLoading = false;
129 Alert.alert(responseJson);
130 }
131 }).catch((error) => {
132 console.error(error);
133 });
134 }, []);
135
136 //setLoading(false);
137
138 //dispatch({ type: 'SIGN_IN', token: 'dummy-auth-token' });
139 },
140 signOut: () => dispatch({ type: 'SIGN_OUT' }),
141 signUp: async data => {
142 // In a production app, we need to send user data to server and get a token
143 // We will also need to handle errors if sign up failed
144 // After getting token, we need to persist the token using `AsyncStorage`
145 // In the example, we'll use a dummy token
146
147 dispatch({ type: 'SIGN_IN', token: 'dummy-auth-token' });
148 },
149 }),
150 []
151 );
152
153
154 if(fontsLoaded){
155 //console.log(state.isLoading);
156 //if(!state.isLoading){
157 return (
158 <AuthContext.Provider value={authContext}>
159 <NavigationContainer>
160 <Stack.Navigator screenOptions={{ headerShown: false }}>
161 {state.isLoading ? (
162 // We haven't finished checking for the token yet
163 <Stack.Screen name="Splash" component={SplashScreen} />
164 ) : state.userToken == null ? (
165 // No token found, user isn't signed in
166 <Stack.Screen
167 name="SignIn"
168 component={SignInScreen}
169 options={{
170 title: 'Sign in',
171 // When logging out, a pop animation feels intuitive
172 animationTypeForReplace: state.isSignout ? 'pop' : 'push',
173 }}
174 />
175 ) : (
176 // User is signed in
177 <Stack.Screen name="Home" component={InScreen} />
178 )}
179 </Stack.Navigator>
180 </NavigationContainer>
181 </AuthContext.Provider>
182 );
183 /*
184 } else {
185 return(
186 <SafeAreaView style={{flex:1,justifyContent:'center',alignItems:'center'}}>
187 <ActivityIndicator size="large"/>
188 </SafeAreaView>
189 );
190 }*/
191 } else {
192 return(
193 <AppLoading
194 startAsync={getFonts}
195 onFinish={()=>setFontsLoaded(true)}
196 onError={console.warn}
197 />
198 );
199 }
200}