USING WEATHER API
WE USE OPEN WEATHER API , SIGNUP AND CREATE AN ACCOUNT , IN THE DROPDOWN, CLICK ON MY API KEYS.
FROM THE GEOCODING API, SELECT THE API URL : https://api.openweathermap.org/data/2.5/weather?q={city name}&appid={API key}
import "./Searchbox.css";
import TextField from "@mui/material/TextField";
import Button from "@mui/material/Button";
import { useState } from "react";
export default function SearchBox() {
let [city, setCity] = useState("");
const API_URL = "https://api.openweathermap.org/data/2.5/weather";
const API_KEY = ***********;
let getWeatherInfo = async () => {
let res = await fetch(`${API_URL}?q=${city}&appid=${API_KEY}&units=metric`);
HERE &units=metric IS USED TO CONVERT THE TEMP (IN KELVIN) INTO CELSIUS.
let jsonRes = await res.json();
console.log(jsonRes);
let result = {
temp: jsonRes.main.temp,
tempMin: jsonRes.main.temp_min,
tempMax: jsonRes.main.temp_max,
humidity: jsonRes.main.humidity,
feels_like: jsonRes.main.feels_like,
weather: jsonRes.weather[0].description,
};
console.log(result);
};
let handleChange = (event) => {
setCity(event.target.value);
};
let handleSubmit = (event) => {
event.preventDefault();
console.log(city);
setCity("");
getWeatherInfo();
};
return (
<div className="SearchBox">
<h2>Find weather</h2>
<form onSubmit={handleSubmit}>
<TextField
id="city"
label="City name"
variant="outlined"
value={city}
required
onChange={handleChange}
/>
<br />
<br />
<Button variant="contained" type="submit">
search
</Button>
</form>
</div>
);
}

Comments
Post a Comment