-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearchBox.jsx
More file actions
86 lines (74 loc) · 2.2 KB
/
Copy pathSearchBox.jsx
File metadata and controls
86 lines (74 loc) · 2.2 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
import TextField from "@mui/material/TextField";
import Button from "@mui/material/Button";
import { useState } from "react";
import "./SearchBox.css";
const SearchBox = ({ updateInfo }) => {
const [city, setCity] = useState("");
const [error, setError] = useState("");
const API_URL = "https://api.openweathermap.org/data/2.5/weather";
const API_KEY = "ADD_HERE_YOUR_OWN_OPEN_WEATHER_API_KEY";
const getWeatherInfo = async () => {
const response = await fetch(
`${API_URL}?q=${city}&appid=${API_KEY}&units=metric`,
);
const jsonResponse = await response.json();
// Check API response before accessing data
if (!response.ok) {
throw new Error(jsonResponse.message);
}
// TODO: Debugg the Code
// console.log(jsonResponse);
const result = {
city: city,
temp: jsonResponse.main.temp,
tempMin: jsonResponse.main.temp_min,
tempMax: jsonResponse.main.temp_max,
humidity: jsonResponse.main.humidity,
feelsLike: jsonResponse.main.feels_like,
weather: jsonResponse.weather[0].description,
};
// TODO: Debugg the Code
// console.log(result);
return result;
};
const handleChange = (e) => {
setCity(e.target.value);
};
// Don't call updateInfo() when fetch fails
const handleSubmit = async (e) => {
e.preventDefault();
try {
const newInfo = await getWeatherInfo();
updateInfo(newInfo);
setError("");
setCity("");
} catch (err) {
if (err.message === "city not found") {
setError("❌ City not found. Please enter a valid city name.");
} else {
setError("⚠️ Something went wrong. Please try again.");
}
}
};
return (
<div className="SearchBox">
<form onSubmit={handleSubmit} className="InputField">
<TextField
id="city"
label="City Name"
variant="outlined"
required
value={city}
onChange={handleChange}
className="outlined-basic"
/>
<Button variant="contained" type="submit">
Search
</Button>
</form>
<br />
{error && <p style={{ color: "red" }}>{error}</p>}
</div>
);
};
export default SearchBox;