/
searchForm.js
75 lines (65 loc) · 1.99 KB
/
searchForm.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
import React, { useState } 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 SearchForm({ onSearch }) {
const [zipCode, setZipCode] = useState('');
const [restaurants, setRestaurants] = useState([]);
const handleSearch = () => {
if (zipCode.trim() !== '') {
api.get('/restaurants', {
params: {
where: { zipCode }, // Send the zipCode as a query parameter
},
})
.then(response => {
// Update the state with the search results
console.log('API Response:', response.data);
setRestaurants(response.data);
// Call the onSearch function with the search results
onSearch(response.data);
})
.catch(error => console.error('Error searching restaurants:', error));
}
};
return (
<div>
<h2>Search Restaurants by Zip Code</h2>
<div className="search-container">
<input
class = "search-text"
type="text"
placeholder="Enter Zip Code"
value={zipCode}
onChange={(e) => setZipCode(e.target.value)}
/>
<br></br>
<br></br>
<button class = "search" onClick={handleSearch}>Search</button>
</div>
{/* Display the search results */}
{restaurants.length > 0 && (
<div>
<h3>Search Results</h3>
<ol>
{restaurants.map(restaurant => (
<li key={restaurant.id}>
{restaurant.name} - {restaurant.address} - {restaurant.phone} - Zip Code: {restaurant.zipCode}
</li>
))}
</ol>
</div>
)}
</div>
);
}
export default SearchForm;