본문 바로가기
깃허브 링크!
react

코알누 react의 lifecycle을 활용한 날씨앱 만들기-5(로딩 스피너)

로딩 스피너 api를 가져온다.

 

import ClipLoader from "react-spinners/ClipLoader";
const[loading,setLoading]=useState(true)
 {loading?(
      <div class="container">
        <ClipLoader color="#f88c6b" loading={loading} size={150} />
        </div>
      ):(
      <div class="container">
      
     
      <WeatherBox weather={weather}/>
     <WeatherButton cities={cities} setCity={setCity}/>
      </div>
      )}

 

 

 

 

 const getCurrnetLocation=()=>{
    navigator.geolocation.getCurrentPosition((position)=>{
        let lat = position.coords.latitude
        let lon = position.coords.longitude
        getWeatherByCurrentLocation(lat,lon);
    });
  };

  const getWeatherByCurrentLocation = async(lat,lon)=>{
    let url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=0b99d295cfa7cbbaa3cdc197e28cacc4&units=metric`;
   
    setLoading(true)
    let response =  await fetch(url)
    let data = await response.json();
    setWeather(data);
    setLoading(false)

  }

 

⌘ loading이라는 props를 통해서 스피너가 보이거나 안보이게 설정가능

 

처음에 loading스피너가 멈추지를 않고 계속 돌아가는데 url을 fetch한 후에 (fetch란 가서 가져온다는 뜻)

데이터 fetch할때만 loading을 true로 설정해서 돌아가게 해주고

데이터가 온 이후로는 더이상 fetch할 필요가 없으니까 false로 변경해준다.

 

 

 

 

⌘ 또 로딩 스피너가 있을때에는 박스를 보여주지 않게 해보자.

return (
    <div>
      {loading?(
      <div class="container">
        <ClipLoader color="#f88c6b" loading={loading} size={150} />
        </div>
      ):(
      <div class="container">
      
     
      <WeatherBox weather={weather}/>
     <WeatherButton cities={cities} setCity={setCity}/>
      </div>
      )}
    </div>
  );