
백엔드에서 받는 것도 실시간으로 적용되는 것이고, 프론트엔드에서 API 요청을 받아오는 것도 똑같이 실시간 적용이라서 프론트에서 받는게 1차적으로 빠르게 할 수 있다고 생각해서 반영하였다.
/** @jsxImportSource @emotion/react */
import { useEffect, useState } from "react";
import axios from "axios";
import { useParams } from "react-router";
import { KioskHomeWeatherImg, KioskHomeWeatherStyle, KioskHomeWeatherTextBox, weatherDescriptionStyle, weatherImg } from "../../style/rentStyle";
const KioskWeather = () => {
const [celsius, setCelsius] = useState(0);
const [windspeed, setWindspeed] = useState(0);
const [weatherIcon, setWeatherIcon] = useState("");
const [weatherDescription, setWeatherDescription] = useState("");
const { id } = useParams();
const API_key = process.env.REACT_APP_WEATHER_API_KEY;
const getWeatherInfo = async (id) => {
let lat, lon;
if (Number(id) === 1) {
lat = "36.10720148408362";
lon = "128.41786543716924";
} else if (Number(id) === 2) {
lat = "36.1028517393142";
lon = "128.3827474679339";
} else if (Number(id) === 3) {
lat = "36.10280020225937";
lon = "128.3823329267556";
}
const response = await axios({
url: `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${API_key}&units=metric`,
method: "GET",
});
if (response) {
setCelsius(response.data.main.temp)
setWindspeed(response.data.wind.speed)
setWeatherIcon(response.data.weather[0].icon);
setWeatherDescription(response.data.weather[0].description);
}
};
useEffect(() => {
getWeatherInfo(id);
}, [id]);
return (
<div css={KioskHomeWeatherStyle}>
<div css={KioskHomeWeatherImg}>
<img
css={weatherImg}
src={`http://openweathermap.org/img/w/${weatherIcon}.png`}
alt="weatherImage"
/>
<div css={weatherDescriptionStyle}>{weatherDescription}</div>
</div>
<div css={KioskHomeWeatherTextBox}>
<p className="celsius">
현재 기온 {Math.round(celsius).toFixed(1)}
<span>⁰</span>
</p>
<p className="windspeed">풍속 : {windspeed}(m/s)</p>
</div>
</div>
);
};
export default KioskWeather;
먼저, useState를 통해 celsius(기온), windspeed(풍속), weatherIcon(날씨 아이콘), weatherDescription(날씨 설명) 상태를 설정합니다.
getWeatherInfo 함수는 주어진 id에 따라 위도와 경도를 설정하고, 이를 바탕으로 OpenWeather API를 호출하여 날씨 정보를 받아옵니다. 이때 API Key는 환경변수에서 가져옵니다.
API 호출의 응답에서, 주요 정보들 (온도, 풍속, 날씨 아이콘, 날씨 설명)을 추출하여 각 상태를 업데이트합니다.
useEffect를 사용하여 컴포넌트가 마운트되거나 id가 변경될 때마다 getWeatherInfo 함수를 호출합니다. 이를 통해 해당 지역의 날씨 정보를 실시간으로 업데이트합니다.
마지막으로, render 메서드에서 현재 날씨 상태를 화면에 표시합니다. 날씨 아이콘 이미지는 OpenWeatherMap에서 제공하는 URL을 이용해 가져옵니다.
그러니까, 이 컴포넌트는 주어진 위치 ID에 따라 해당 지역의 실시간 날씨 정보를 가져와서 화면에 표시하는 역할을 합니다. 이 때 날씨 정보에는 온도, 풍속, 날씨 아이콘, 날씨 설명 등이 포함됩니다.