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