날씨 API 사용해보기

임성은·2023년 4월 18일
0

https://openweathermap.org/

이전에도 테스트 삼아 사용해봤던 Api라서 생각보다 간단하고 빠르게 구현 하였다!

키는 .env 파일에서 관리를 해주고 api 폴더를 만들어 안에 밑의 파일을 만들어줍니다.

weatherApi.js

const APIkey = process.env.REACT_APP_WEATHER_API_KEY;


export const getWeather = async (lat, lon) => {
  const apiUrl = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${APIkey}`

  const response = await fetch(apiUrl);
  return await response.json();
};

Info.js

  useEffect(() => {
    navigator.geolocation.getCurrentPosition(position => {
      const { latitude, longitude } = position.coords;
      getWeather(latitude, longitude)
        .then(data => setWeatherData(data))

        .catch(error => (error));
    });
  }, []);


  if (!weatherData) {
    return <div>Loading...</div>;
  }

  let weatherIcon;
  if (weatherData.weather[0].main === 'Rain') {
    weatherIcon = <img src="./img/rain.gif" alt="Rain" />;
  } else if (weatherData.weather[0].main === 'Clouds') {
    weatherIcon = <img src="./img/clouds.gif" alt="Cloudy" />;
  } else if (weatherData.weather[0].main === 'Clear') {
    weatherIcon = <img src="./img/sun.gif" alt="Sunny" />;
  } else if (weatherData.weather[0].main === 'Atmosphere') {
    weatherIcon = <img src="./img/foggy.gif" alt="foggy" />;
  } else if (weatherData.weather[0].main === 'Snow') {
    weatherIcon = <img src="./img/snow.gif" alt="snow" />;
  } else if (weatherData.weather[0].main === 'Drizzle') {
    weatherIcon = <img src="./img/rain.gif" alt="drizzle" />;
  } else if (weatherData.weather[0].main === 'Thunderstorm') {
    weatherIcon = <img src="./img/clouds.gif" alt="Thunderstorm" />;
  }

사용할 컴포넌트에서 불러와줍니다.

전 날씨를 불러와서 해당 날씨에 맞는 아이콘을 보여주려고 합니다.

네 잘 나옵니다! 요즘 계속 날이 흐렸는데 얼른 날이 좋아지면 좋겠습니다!^0^

profile
개발자의 길에 당차게 들어서다!!

0개의 댓글