useEffect(() => {
getCurrentLocation();
getWeatherByCity();
console.log(city);
}, [<u>**city**</u>]);
위의 코드는 에러 코드이다.
위의 코드로는 에러가 발생할 수 밖에 없다.
getWeatherByCity이라는 함수의 url은 city를 넘겨받아야 data를 받아올 수 있는데,
첫 화면이 랜더링될 때는 넘겨받는 city값이 null이기 때문에 화면을 구성할 수 없기 때문이다.
따라서 조건에 따라 UI를 구성하는 useEffect 함수를 만들어줘야한다.
*또한, city가 변경될때마다 재랜더링을 해야하기 때문에 defendency array에 city를 넣어준다.
🚩 개선하기
useEffect(() => {
{
if (!city) {
getCurrentLocation();
} else {
getWeatherByCity();
console.log(city);
}
}
}, [city]);
🚩 삼항연산자로 압축하기
useEffect(() => {
{
!city ? getCurrentLocation() : getWeatherByCity();
}
}, [city]);
useEffect(() => {
{
if (**city === "current"**) {
getCurrentLocation();
} else {
getWeatherByCity();
}
}
}, [city]);
export default function CityButton({ cities, setCity }) {
return (
<div className="btn_wrap">
<button onClick={() => **setCity("current")**}>CURRENT LOCATION</button>
{cities.map((city, idx) => (
<button key={idx} onClick={() => setCity(city)}>
{city.toUpperCase()}
</button>
))}
</div>
);
}