-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWeather.jsx
More file actions
94 lines (86 loc) · 3.33 KB
/
Weather.jsx
File metadata and controls
94 lines (86 loc) · 3.33 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
87
88
89
90
91
92
93
94
import React, { useEffect, useState } from "react";
import styles from "./style.module.css";
const Weather = () => {
const [search, setSearch] = useState("");
const [clue, setClue] = useState([]);
const [selectedCity, setSelectedCity] = useState(null);
const [weather, setWeather] = useState(null);
const handleChangeSearch = async (e) => {
try {
setSearch(e.target.value);
const resSearch = await fetch(
`https://api.openweathermap.org/geo/1.0/direct?q=${e.target.value},RU&limit=5&appid=4841d6c54ff9976a8984497d734c60fd&lang=ru`
);
const res = await resSearch.json();
setClue(res);
} catch (error) {
console.log("Error");
}
};
const handleSelectCity = (city) => {
setSelectedCity(city);
setSearch(city.name);
setClue([]);
};
const getWeather = async (lat, lon) => {
try {
const res = await fetch(
`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=4841d6c54ff9976a8984497d734c60fd&lang=ru&units=metric`
);
let data = await res.json();
setWeather(data);
} catch (error) {
console.log("Error");
}
};
useEffect(() => {
if (selectedCity) {
getWeather(selectedCity.lat, selectedCity.lon);
}
}, [selectedCity]);
return (
<div className={styles.app}>
<div className={styles.container}>
<div className={styles.searchBox}>
<input
className={styles.searchInput}
placeholder="Введите город"
type="text"
onChange={handleChangeSearch}
value={search}
/>
{clue.length > 0 && (
<ul className={styles.suggestionsList}>
{clue.map((city) => (
<li
key={`${city.lat}-${city.lon}`}
className={styles.suggestionItem}
onClick={() => handleSelectCity(city)}
>
{city.name}, {city.country}
</li>
))}
</ul>
)}
</div>
{weather && (
<div className={styles.weatherCard}>
<h2 className={styles.cityName}>{weather.name}</h2>
<p className={styles.temperature}>
{Math.round(weather.main.temp)}°C
</p>
<p className={styles.description}>
{weather.weather[0].description}
</p>
<img
className={styles.weatherIcon}
src={`https://openweathermap.org/img/wn/${weather.weather[0].icon}@2x.png`}
alt={weather.weather[0].description}
/>
</div>
)}
</div>
</div>
);
};
export default Weather;