-
Notifications
You must be signed in to change notification settings - Fork 0
/
Emergencycontacts.js
201 lines (172 loc) · 5.55 KB
/
Emergencycontacts.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
import AsyncStorage from '@react-native-async-storage/async-storage';
import React, { useState } from 'react';
import { View, Text, TextInput, Button, FlatList,
TouchableOpacity,
StyleSheet, } from 'react-native';
import { Linking } from 'react-native';
const [searchTerm, setSearchTerm] = useState('');
// function to store contacts
const storeContacts = async (contacts) => {
try {
const jsonValue = JSON.stringify(contacts);
await AsyncStorage.setItem('emergencyContacts', jsonValue);
} catch (error) {
console.error('Error storing contacts:', error);
}
};
// function to retrieve contacts
const getContacts = async () => {
try {
const jsonValue = await AsyncStorage.getItem('emergencyContacts');
const fetchedContacts = jsonValue != null ? JSON.parse(jsonValue) : [];
// Ensure fetchedContacts is an array of objects with a "name" property
if (!Array.isArray(fetchedContacts) || !fetchedContacts.every((contact) => contact.name)) {
console.error('Error: Invalid contact data format in AsyncStorage');
// Handle the error gracefully (e.g., display an error message or set an empty array)
setContacts([]);
return;
}
setContacts(fetchedContacts);
} catch (error) {
console.error('Error retrieving contacts:', error);
}
};
const filteredContacts = contacts.filter((contact) =>
contact.name.toLowerCase().includes(searchTerm.toLowerCase())
);
const renderItem = ({ item }) => (
<TouchableOpacity onPress={() => handleCall(item.phoneNumber)}>
<View style={styles.contactItem}>
<Text style={styles.contactName}>{item.name}</Text>
{item.category && <Text style={styles.contactCategory}>({item.category})</Text>}
</View>
</TouchableOpacity>
);
const AddContactScreen = ({ navigation }) => {
const [name, setName] = useState('');
const [phoneNumber, setPhoneNumber] = useState('');
const [category, setCategory] = useState(''); // Optional for contact category
const handleSaveContact = async () => {
// Basic validation (optional)
if (!name || !phoneNumber) {
alert('Please enter a name and phone number');
return;
}
const newContact = {
name,
phoneNumber,
category, // Include category if used
};
try {
// Get existing contacts (or an empty array)
const contacts = await getContacts();
// Add the new contact to the list
contacts.push(newContact);
// Store the updated contact list in AsyncStorage
await storeContacts(contacts);
// Clear input fields and optionally navigate back
setName('');
setPhoneNumber('');
setCategory(''); // Clear category if used
navigation.goBack(); // Assuming navigation prop is passed
} catch (error) {
console.error('Error saving contact:', error);
alert('An error occurred while saving the contact'); // Inform user
}
};
useEffect(() => {
getContacts(); // Fetch contacts on component mount
}, []);
const handleCall = (phoneNumber) => {
Linking.openURL(`tel:${phoneNumber}`); // Dial the phone number
};
const renderItem = ({ item }) => (
<TouchableOpacity onPress={() => handleCall(item.phoneNumber)}>
<View style={styles.contactItem}>
<Text style={styles.contactName}>{item.name}</Text>
{item.category && <Text style={styles.contactCategory}>({item.category})</Text>}
</View>
</TouchableOpacity>
);
// Functions to store and retrieve contacts are assumed to be defined elsewhere (see previous discussions)
return (
<View style={styles.container}>
<Text style={styles.title}>Add Emergency Contact</Text>
<TextInput
style={styles.input}
placeholder="Name"
value={name}
onChangeText={setName}
/>
<TextInput
style={styles.input}
placeholder="Phone Number"
value={phoneNumber}
onChangeText={setPhoneNumber}
keyboardType="phone-pad" // Optional keyboard type for phone numbers
/>
<TextInput
style={styles.input} // Adjust styling if needed for category
placeholder="Category (Optional)"
value={category}
onChangeText={setCategory}
/>
<Button title="Save Contact" onPress={handleSaveContact} />
{/* Search bar */}
<TextInput
style={styles.searchInput}
placeholder="Search Contacts"
value={searchTerm}
onChangeText={setSearchTerm}
/>
{/* Contact list */}
{filteredContacts.length > 0 ? (
<FlatList
data={filteredContacts}
renderItem={renderItem}
keyExtractor={(item) => item.name} // Unique key for each item
/>
) : (
<Text style={styles.noContactsText}>No contacts found.</Text>
)}
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 20,
},
title: {
fontSize: 24,
marginBottom: 20,
},
input: {
height: 40,
borderWidth: 1,
borderColor: 'gray',
padding: 8,
marginBottom: 10,
},
searchInput: {
// Styles for search bar input
fontSize: 16,
padding: 10,
backgroundColor: '#f5f5f5', // Light background
borderRadius: 5, // Rounded corners
},
contactItem: {
padding: 15,
borderBottomWidth: 1,
borderBottomColor: '#ddd', // Light border
},
contactName: {
fontSize: 18,
fontWeight: 'bold',
},
contactCategory: {
fontSize: 14,
color: '#ccc', // Light gray text for category
},
});
export default Emergencycontacts;