한 걸음씩
[React] classy-weather project [미완] 본문
export default function App() {
const [value, setValue] = useState('')
return (
<div className="app">
<h2>Classy weather</h2>
<Form value={value} setValue={setValue} />
<Weather value={value} />
</div>
)
}
Form, Weather 컴포넌트 렌더링 하는 부모 컴포넌트 App
function Form({ value, setValue }) {
function handleSubmit(e) {
e.preventDefault()
if (!value.length) return
setValue(e.target.value)
}
return (
<form onSubmit={handleSubmit}>
<input
placeholder="search from location"
value={value}
onChange={e => setValue(e.target.value)}
/>
</form>
)
}
입력 값을 받는 입력 폼
function Weather({ value }) {
const [location, setLocation] = useState(null)
const [weatherData, setweatherData] = useState([])
useEffect(() => {
async function getWeather() {
try {
const res = await fetch(
`https://geocoding-api.open-meteo.com/v1/search?name=${value}`
)
const data = await res.json()
// console.log(data.results[0])
if (data.results && data.results.length > 0) {
const { latitude, longitude, timezone, name, country_code } =
data.results[0]
setLocation({ latitude, longitude, timezone, name, country_code })
} else {
console.error('No results found for the location')
}
} catch (error) {
console.error('Error fething data: ', error)
}
}
// 불필요한 api호출 방지
if (value) {
getWeather()
}
}, [value])
// console.log(location)
useEffect(() => {
async function geoWeather() {
if (!location) return
const res = await fetch(
`https://api.open-meteo.com/v1/forecast?latitude=${location.latitude}&longitude=${location.longitude}&timezone=${location.timezone}&daily=weathercode,temperature_2m_max,temperature_2m_min`
)
const data = await res.json()
setweatherData(data.daily)
}
// console.log(weatherData)
// console.log(weatherData.time[0])
geoWeather()
}, [location])
return (
<div className="weather">
<h4>Weather {value}</h4>
<ul>
{Array.isArray(weatherData) &&
weatherData.map((dayData, i) => (
<li key={i}>
<div className="day">{dayData.time[0]}</div>
</li>
))}
</ul>
</div>
)
}
날씨 데이터를 받아오고 화면에 렌더링 하는 부분
발생한 문제) 첫 번째 useEffect에서 api 호출이 정상적으로 이루어진 것을 콘솔로 출력하여 확인 완료
두 번째 useEffect에서 api 호출이 정상적으로 이루어진 것을 콘솔로 출력하여 확인 완료
화면 렌더링하는 JSX 코드 부분에서 weatherData를 map메서드 사용해서 렌더링 시도 했지만
아무것도 보이지 않는다는 문제 발생.
weatherData 받아오는 useEffect 내에서 콘솔로 확인했을 때는 문제가 없어서 어떻게 해결해야 할지 모르겠다
api를 정상적으로 호출을 받아도 화면 렌더링이 되었다 안되었다 하는 걸 보면 api 자체에 문제가 있을 수 있다는 의심이 살짝...
'React' 카테고리의 다른 글
[React] useReducer (1) | 2024.02.05 |
---|---|
[React] React-Router (0) | 2024.02.05 |
[React] Custom Hooks, Refs and More state (0) | 2024.01.27 |
[React] Effects and Data Fetching (0) | 2024.01.27 |
[React] How React works (0) | 2024.01.26 |