-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathContactList.js
More file actions
61 lines (55 loc) · 2.33 KB
/
ContactList.js
File metadata and controls
61 lines (55 loc) · 2.33 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
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import './Contact.css';
const ContactList = ({ onContactSelected, refreshKey }) => {
const [contacts, setContacts] = useState([]);
const [error, setError] = useState(null);
const fetchContacts = async () => {
try {
const response = await axios.get('/api/contacts');
setContacts(response.data);
setError(null); // Clear any previous errors
} catch (err) {
console.error('There was an error fetching the contacts!', err);
setError('Failed to load contacts. Please ensure the backend is running.');
}
};
// This useEffect now depends on refreshKey, so it re-fetches when a contact is added/deleted/updated
useEffect(() => {
fetchContacts();
}, [refreshKey]);
const handleDelete = async (contactId) => {
try {
await axios.delete(`/api/contacts/${contactId}`);
// Refresh the contact list after successful deletion
fetchContacts();
} catch (err) {
console.error('Failed to delete contact:', err);
setError('Failed to delete contact.');
}
};
return (
<div className="contact-list-container">
<h2>Contact List</h2>
{error && <div className="alert-error">{error}</div>}
<div className="contact-grid">
{contacts.length > 0 ? (
contacts.map(contact => (
<div key={contact.contactId} className="contact-card">
<h3>{contact.name}</h3>
<p><strong>Email:</strong> {contact.email}</p>
<p><strong>Phone:</strong> {contact.phone}</p>
<div className="contact-actions">
<button onClick={() => onContactSelected(contact)}>Edit</button>
<button onClick={() => handleDelete(contact.contactId)} className="delete-button">Delete</button>
</div>
</div>
))
) : (
<p>No contacts found. Add a new contact using the form above. ➕</p>
)}
</div>
</div>
);
};
export default ContactList;