-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.jsx
More file actions
101 lines (92 loc) · 2.59 KB
/
Copy pathApp.jsx
File metadata and controls
101 lines (92 loc) · 2.59 KB
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
import { useEffect, useState } from "react";
import { Alert, Text, View } from "react-native";
import AsyncStorage from "@react-native-async-storage/async-storage";
import GoalInput from "./components/goal-input";
import GoalList from "./components/goal-list";
export default function App() {
const [isLoadingData, setIsLoadingData] = useState(true);
const [goalList, setGoalList] = useState([]);
// load all saved goals
useEffect(() => {
AsyncStorage.getItem("goals")
.then((data) => {
const savedGoals = data !== null ? JSON.parse(data) : [];
setGoalList(savedGoals);
})
.catch(() =>
Alert.alert("Error", "Fail to load goals", [
{ text: "OK", style: "cancel" },
])
)
.finally(() => setIsLoadingData(false));
}, []);
// save goals after every list mutation
useEffect(() => {
AsyncStorage.setItem("goals", JSON.stringify(goalList)).catch(() =>
Alert.alert("Error", "Fail to load goals", [
{ text: "OK", style: "cancel" },
])
);
}, [goalList]);
const addGoal = async (newGoal) => {
setGoalList((prevs) => [
{
id: `${prevs.length + 1}-${new Date().toISOString()}`,
date: new Date().toISOString(),
text: newGoal,
},
...prevs,
]);
};
const deleteGoal = (id) => {
Alert.prompt(
"Delete Goals",
"Are you sure you want to delete this goal ?",
[
{
text: "Cancel",
style: "cancel",
},
{
text: "OK",
style: "destructive",
onPress: () =>
setGoalList((prevs) => prevs.filter((p) => p.id !== id)),
},
]
);
Alert.alert("Delete Goals", "Are you sure you want to delete this goal ?", [
{
text: "Cancel",
style: "cancel",
},
{
text: "OK",
style: "destructive",
onPress: () => setGoalList((prevs) => prevs.filter((p) => p.id !== id)),
},
]);
};
return (
<View style={{ flex: 1 }}>
{/* inputs */}
<View className="pb-5 px-3 pt-12">
<Text className="font-bold text-slate-900 text-3xl">iGoal</Text>
<GoalInput onAddGoal={addGoal} />
</View>
{/* list */}
<View
className="border-t shadow-inner border-slate-200 bg-slate-100"
style={{ flex: 1 }}
>
{isLoadingData ? (
<Text className="text-center text-lg mt-6 text-slate-400">
Loading Goals...
</Text>
) : (
<GoalList data={goalList} deleteGoal={deleteGoal} />
)}
</View>
</View>
);
}