-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApp.provider.js
68 lines (56 loc) · 1.53 KB
/
App.provider.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
import React from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage';
const storageKey = 'my-app-data';
const getAppData = async () => {
try {
const data = await AsyncStorage.getItem(storageKey);
if (data) {
return JSON.parse(data);
}
return null;
} catch {
return null;
}
};
const setAppData = async (newData) => {
try {
await AsyncStorage.setItem(storageKey, JSON.stringify(newData));
} catch {}
};
const AppContext = React.createContext();
export const AppProvider = ({ children }) => {
const [moodList, setMoodList] = React.useState([]);
const handleSelectMood = React.useCallback((mood) => {
setMoodList((current) => {
const newValue = [...current, { mood, timestamp: Date.now() }];
setAppData({ moods: newValue });
return newValue;
});
}, []);
const handleDeleteMood = React.useCallback((mood) => {
setMoodList((current) => {
const newValue = current.filter(
(item) => item.timestamp !== mood.timestamp,
);
setAppData({ moods: newValue });
return newValue;
});
}, []);
React.useEffect(() => {
const getDataFromStorage = async () => {
const data = await getAppData();
if (data) {
setMoodList(data.moods);
}
};
getDataFromStorage();
}, []);
return (
<AppContext.Provider
value={{ moodList, handleSelectMood, handleDeleteMood }}
>
{children}
</AppContext.Provider>
);
};
export const useAppContext = () => React.useContext(AppContext);