-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSearchBox.jsx
58 lines (52 loc) · 1.72 KB
/
SearchBox.jsx
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
import TextField from '@mui/material/TextField';
import Button from '@mui/material/Button';
import "./SearchBox.css";
import { useState } from 'react';
export default function SearchBox({updateInfo}){
let [city,setCity] = useState("");
let [error,setError] = useState(false);
const API_URL = "https://api.openweathermap.org/data/2.5/weather";
const API_KEY = "f9a05d12d6f99427becf523a19b3047f";
// "1031e82180981b48e6b9fba105594774";
let getWeatherInfo = async() => {
try{
let response = await fetch(`${API_URL}?q=${city}&appid=${API_KEY}&units=metric`);
let jsonResponse = await response.json();
let result = {
city: city,
temp: jsonResponse.main.temp,
tempMin: jsonResponse.main.temp_main,
tempMax: jsonResponse.main.temp_max,
humidity: jsonResponse.main.humidity,
feelsLike: jsonResponse.main.feels_Like,
weather: jsonResponse.weather[0].description,
};
console.log(result);
}catch(error){
throw err;
}};
let handleChange =(evt) => {
setCity(evt.target.value);
};
let handleSubmit = async(evt) => {
try{
evt.preventDefault();
console.log(city);
setCity = ("");
let newInfo = await getWeatherInfo();
updateInfo(newInfo);
}catch(err){
setError(true);
}};
return(
<div className='SearchBox'>
<form onSubmit={handleSubmit}>
<TextField id="city" label="City Name" variant="outlined" required value={city} onChange={handleChange}/>
<br></br>
<br></br>
<Button variant="contained" type='submit'>Search</Button>
{error && <p>No such place exist</p>}
</form>
</div>
);
}