/
restaurantList.js
54 lines (47 loc) · 1.59 KB
/
restaurantList.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
import React, { useState, useEffect } from 'react';
import axios from 'axios';
const getAuthToken = () => {
// Replace this with your logic to obtain the token
return 'ADD_YOUR_TOKEN_HERE';
};
const api = axios.create({
baseURL: 'http://localhost:3000/api', // Adjust the base URL to your API endpoint
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${getAuthToken()}`, // Attach the token here
},
});
function RestaurantList() {
const [restaurants, setRestaurants] = useState([]);
// Fetch restaurants when component mounts
useEffect(() => {
api.get('/restaurants')
.then(response => {
setRestaurants(response.data);
})
.catch(error => console.error('Error fetching restaurants:', error));
}, []);
const handleDelete = (restaurantId) => {
api.delete(`/restaurants/${restaurantId}`)
.then(() => {
// Filter out the deleted restaurant
setRestaurants(restaurants.filter(restaurant => restaurant.id !== restaurantId));
})
.catch(error => console.error('Error deleting restaurant:', error));
};
return (
<div>
<h2>Restaurants List</h2>
{restaurants.map(restaurant => (
<div class = "res-list" key={restaurant.id}>
<h3>{restaurant.name}</h3>
<p>{restaurant.address}</p>
<p>{restaurant.phone}</p>
<p>Zip Code: {restaurant.zipCode}</p> {/* Display the Zip Code */}
<button class='btn' onClick={() => handleDelete(restaurant.id)}>Delete</button>
</div>
))}
</div>
);
}
export default RestaurantList;