-
Notifications
You must be signed in to change notification settings - Fork 2
/
App.js
115 lines (104 loc) · 2.4 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
import React from 'react';
import BottomNavigator from './routes/bottomNavigation';
import AppContext from './assets/globals/appContext';
import { useState } from 'react';
import { favoriteFoods } from './assets/controller/query';
import { useEffect } from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage';
export default function App() {
const getData = async () => {
try{
const value = JSON.parse(await AsyncStorage.getItem('favorites'));
// console.log(value);
return value != null ? value : [];
}
catch(e){
alert(e);
}
}
const saveData = async (foodIds) => {
try {
const value = JSON.stringify(foodIds);
await AsyncStorage.setItem('favorites', value);
}
catch (e){
alert(e);
}
}
const [favs, setFavs] = useState();
const [foods, setFoods] = useState();
useEffect(() => {
getData()
.then(data => {
setFavs(data != null ? data : []);
fetchFoods(data != null ? data : []);
})
.catch(error => {
alert(error);
})
}, [])
const fetchFoods = (favFoods) => {
favoriteFoods(favFoods)
.then(data => {
setFoods(data);
})
.catch(error => {
alert(error)
})
}
const addFavorites = (id) => {
const tempFavs = favs;
if(!tempFavs.find((food) => food == id)){
tempFavs.push(id);
}
setFavs(tempFavs);
favoriteFoods(tempFavs)
.then(data => {
setFoods(data);
})
.catch(error => {
alert(error)
});
saveData(tempFavs);
}
const clearFavorites = () => {
const tempFavs = [];
setFavs(tempFavs);
favoriteFoods(tempFavs)
.then(data => {
setFoods(data);
})
.catch(error => {
alert(error)
});
saveData(tempFavs);
}
const deleteFavorites = (id) => {
const tempFavs = favs;
const index = tempFavs.indexOf(id);
if(index > -1){
tempFavs.splice(index, 1);
}
setFavs(tempFavs);
favoriteFoods(tempFavs)
.then(data => {
setFoods(data);
})
.catch(error => {
alert(error)
});
saveData(tempFavs);
}
const favorites = {
favs: favs,
foods: foods,
addFavorites,
clearFavorites,
deleteFavorites,
}
return (
<AppContext.Provider value={ favorites }>
<BottomNavigator />
</AppContext.Provider>
);
}