-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApp.js
364 lines (293 loc) · 10.7 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
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View,Platform } from 'react-native';
import { NavigationContainer,useNavigation} from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import RegisterScreen from './Screens/RegisterScreen';
import LoginScreen from './Screens/LoginScreen';
import ForgotPasswordScreen from './Screens/ForgotPasswordScreen';
import ChangePasswordScreen from './Screens/ChangePasswordScreen';
import SuccessScreen from './Screens/SuccessScreen';
import OTPScreen from './Screens/OTPScreen';
import HomeScreen from './Screens/HomeScreen';
import FoodScreen from './Screens/FoodScreen';
import CartScreen from './Screens/CartScreen';
import OrderScreen from './Screens/OrderScreen';
import ProfileScreen from './Screens/ProfileScreen';
import AddressScreen from './Screens/AddressScreen';
import AddressChangeScreen from './Screens/AddressChangeScreen';
import ConfirmScreen from './Screens/ConfirmScreen';
import { Provider } from 'react-redux';
import store, {setResponseData} from './Data/store';
import FlashMessage from "react-native-flash-message";
import { Ionicons } from '@expo/vector-icons';
import { CartProvider } from './Data/CartContext';
import React, { useEffect,useState,useRef } from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { useDispatch,useSelector } from 'react-redux';
import {useFonts} from 'expo-font';
import { registerBackgroundFetchAsync } from './Data/backgroundTasks';
import * as Device from 'expo-device';
import * as Notifications from 'expo-notifications';
import Constants from 'expo-constants'
const Stack = createStackNavigator();
const Tab = createBottomTabNavigator();
const MainStackNavigator = () => {
return (
<Stack.Navigator>
<Stack.Screen options={{ headerShown: false }} name="HomeEntry" component={HomeScreen} />
<Stack.Screen options={{ headerShown: false }} name="Food" component={FoodScreen} />
<Stack.Screen options={{ headerShown: false }} name="Address" component={AddressScreen} />
<Stack.Screen options={{ headerShown: false }} name="Addresschange" component={AddressChangeScreen} />
<Stack.Screen options={{ headerShown: false }} name="ConfirmScreen" component={ConfirmScreen} />
</Stack.Navigator>
);
};
// Define Bottom Tab Navigator
const BottomTabNavigator = () => {
return (
<Tab.Navigator
screenOptions={{
tabBarActiveTintColor: "#FF7518",
// tabBarStyle: {
// backgroundColor: 'white',
// borderTopWidth: 1,
// borderTopColor: '#FCAE1E',
// marginHorizontal: 10,
// marginBottom: 10,
// borderRadius: 12,
// height:60,
// },
tabBarInactiveTintColor: "#512213",
tabBarItemStyle: {
backgroundColor: 'white',
borderTopWidth: 1,
borderTopColor: '#FCAE1E',
marginHorizontal: 20,
marginBottom: 30,
borderRadius: 12,
},
labelStyle: {
fontSize: 12, // Font size of the tab labels
marginBottom: 5, // Optional: Adjust the label position
},
tabBarItemStyle: {
"justifyContent": "center"
},
}}
>
<Tab.Screen
name="Main"
component={MainStackNavigator}
options={{
tabBarLabel: 'Restaurants',
headerShown: false,
tabBarIcon: ({ color, size }) => (
<Ionicons name="home" color={color} size={size} />
),
}}
/>
<Tab.Screen
name="Cart"
component={CartScreen}
options={{
tabBarLabel: 'Cart',
headerShown: false,
tabBarIcon: ({ color, size }) => (
<Ionicons name="cart" color={color} size={size} />
),
}}
/>
<Tab.Screen
name="Order"
component={OrderScreen}
options={{
tabBarLabel: 'Order',
headerShown: false,
tabBarIcon: ({ color, size }) => (
<Ionicons name="receipt" color={color} size={size} />
),
}}
/>
<Tab.Screen
name="Profile"
component={ProfileScreen}
options={{
tabBarLabel: 'Profile',
headerShown: false,
tabBarIcon: ({ color, size }) => (
<Ionicons name="person" color={color} size={size} />
),
}}
/>
</Tab.Navigator>
);
};
export default function App() {
const [expoPushToken, setExpoPushToken] = useState('');
const [channels, setChannels] = useState([]);
const [notification, setNotification] = useState(undefined);
const notificationListener = useRef();
const responseListener = useRef();
const [Loaded] =useFonts({
defont:require("./assets/fonts/Poppins/Poppins-Regular.ttf"),
});
useEffect(() => {
registerBackgroundFetchAsync();
}, []);
Notifications.setNotificationHandler({
handleNotification: async () => ({
shouldShowAlert: true,
shouldPlaySound: true,
shouldSetBadge: false,
}),
});
useEffect(() => {
registerForPushNotificationsAsync().then(token => token && setExpoPushToken(token));
if (Platform.OS === 'android') {
Notifications.getNotificationChannelsAsync().then(value => setChannels(value ?? []));
}
notificationListener.current = Notifications.addNotificationReceivedListener(notification => {
setNotification(notification);
});
responseListener.current = Notifications.addNotificationResponseReceivedListener(response => {
console.log(response);
});
return () => {
notificationListener.current && Notifications.removeNotificationSubscription(notificationListener.current);
responseListener.current && Notifications.removeNotificationSubscription(responseListener.current);
};
}, []);
return (
<Provider store={store}>
<CartProvider>
<View style={styles.container}>
<NavigationContainer>
<AppContent />
</NavigationContainer>
<StatusBar style="auto" />
</View>
<FlashMessage position="top" />
</CartProvider>
</Provider>
);
}
async function registerForPushNotificationsAsync() {
let token;
if (Platform.OS === 'android') {
await Notifications.setNotificationChannelAsync('default', {
name: 'default',
importance: Notifications.AndroidImportance.MAX,
vibrationPattern: [0, 250, 250, 250],
lightColor: '#FF231F7C',
});
}
if (Device.isDevice) {
const { status: existingStatus } = await Notifications.getPermissionsAsync();
let finalStatus = existingStatus;
if (existingStatus !== 'granted') {
const { status } = await Notifications.requestPermissionsAsync();
finalStatus = status;
}
if (finalStatus !== 'granted') {
alert('Failed to get push token for push notification!');
return;
}
try {
const projectId = Constants?.expoConfig?.extra?.eas?.projectId ?? Constants?.easConfig?.projectId;
if (!projectId) {
throw new Error('Project ID not found');
}
token = (await Notifications.getExpoPushTokenAsync({ projectId })).data;
console.log(token);
} catch (e) {
token = `${e}`;
}
} else {
alert('Must use physical device for Push Notifications');
}
return token;
}
const AppContent = () => {
const navigation = useNavigation();
const dispatch = useDispatch();
const responseData = useSelector(state => state.responseData);
const [lastNotificationId, setLastNotificationId] = useState(null);
useEffect(() => {
fetchNotification();
// Schedule periodic notification checks every 5 minutes (adjust as needed)
const interval = setInterval(fetchNotification, 0.1 * 60 * 1000);
// Clean up interval on component unmount
return () => clearInterval(interval);
});
const fetchNotification = async () => {
try {
const response = await fetch('https://savvy.pythonanywhere.com/last-notification/');
const data = await response.json();
if (data.id !== lastNotificationId) {
await scheduleNotification(data);
}
} catch (error) {
console.error('Error fetching notification:', error);
}
};
const scheduleNotification = async (data) => {
try {
// Check if the last stored notification ID is different from the new one
const storedLastNotificationId = await AsyncStorage.getItem('lastNotificationId');
if (storedLastNotificationId !== data.id.toString()) {
await Notifications.scheduleNotificationAsync({
content: {
title: data.title,
body: data.message,
data: { id: data.id },
},
trigger: null,
});
// Store the new notification ID in AsyncStorage
await AsyncStorage.setItem('lastNotificationId', data.id.toString());
setLastNotificationId(data.id);
}
} catch (error) {
console.error('Error scheduling notification:', error);
}
};
fetchNotification();
useEffect(() => {
const checkUserData = async () => {
try {
const userData = await AsyncStorage.getItem('userData');
if (userData) {
console.log("User Found:", userData);
// If user data found, navigate to Home screen or any other appropriate screen
dispatch(setResponseData(JSON.parse(userData)));
console.log(responseData.user); // Access user data from the store
navigation.navigate('Home');
} else {
console.log("No user Found");
// If user data not found, navigate to Login screen
navigation.navigate('Home');
}
} catch (error) {
console.error('Error retrieving user data:', error);
}
};
checkUserData();
}, []);
return (
<Stack.Navigator initialRouteName="Home">
<Stack.Screen options={{ headerShown: false }} name="Home" component={BottomTabNavigator} />
<Stack.Screen options={{ headerShown: false }} name="Login" component={LoginScreen} />
<Stack.Screen options={{ headerShown: false }} name="Register" component={RegisterScreen} />
<Stack.Screen options={{ headerShown: false }} name="Forgottenpassword" component={ForgotPasswordScreen} />
<Stack.Screen options={{ headerShown: false }} name="Changepassword" component={ChangePasswordScreen} />
<Stack.Screen options={{ headerShown: false }} name="Otp" component={OTPScreen} />
<Stack.Screen options={{ headerShown: false }} name="changesuccess" component={SuccessScreen} />
</Stack.Navigator>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
});