-
Notifications
You must be signed in to change notification settings - Fork 0
/
App.js
85 lines (73 loc) · 2.37 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
import { NavigationContainer, DefaultTheme} from '@react-navigation/native';
import { useState, useEffect } from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage';
import AppNavigation from './AppNavigation';
import AuthContext from './AuthContext';
import { io } from "socket.io-client";
import { StatusBar } from 'expo-status-bar';
const MyTheme = {
...DefaultTheme,
colors: {
...DefaultTheme.colors,
background: 'white'
},
};
export default function App() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
const [userData, setUserData] = useState(null);
const [notifs, setNotifs] = useState([])
//const socket = io("https://api-smarthome.onrender.com");
//const socket = io("http://10.0.2.2:3000");
const socket = io("https://smarthome-api.onrender.com")
const fetchUser = async () => {
try {
const value = await AsyncStorage.getItem('userData')
if (value != null) setUserData(JSON.parse(value))
} catch(e) {
console.log(e)
}
};
const fetchNotif = async () => {
try {
const value = await AsyncStorage.getItem('notifs')
if (value != null) setNotifs(JSON.parse(value))
} catch (e) {
console.log(e)
}
};
useEffect(() => {
fetchUser();
fetchNotif()
}, [isLoggedIn]);
useEffect(() => {
socket.on('notif received', (newNotif) => {
setNotifs(prev => {
let isDup = false
prev.forEach(notif => {
if (notif._id === newNotif._id) isDup = true
})
if (isDup) return prev
const updatedNotifs = [newNotif, ...prev]
AsyncStorage.setItem('notifs', JSON.stringify(updatedNotifs))
return updatedNotifs
})
})
})
const login = () => {
setIsLoggedIn(true);
console.log('Login Status: ', isLoggedIn)
};
const logout = () => {
setIsLoggedIn(false);
console.log('Login Status: ', isLoggedIn)
};
console.log(userData)
return (
<AuthContext.Provider value={{ isLoggedIn, userData, setUserData, login, logout, notifs, setNotifs, socket }}>
<NavigationContainer theme={MyTheme}>
<StatusBar backgroundColor="#EBF8FF" style='dark-content'/>
<AppNavigation />
</NavigationContainer>
</AuthContext.Provider>
);
}