React 날씨 정보 API 호출

곽지욱·2024년 9월 2일
0

React

목록 보기
7/12
post-thumbnail

첫번째로 사이트에서 APIKEY를 가져와야 한다.

https://openweathermap.org

위의 링크를 타고 들어가서 회원가입을 한 후에 자기 닉네임 -> my API Keys 에 들어가서 API 키를 가져오면 된다.

1. 위치 정보 가져오기

  • 우선 사용자의 현재 위치를 가져오기 위해navigator.geolacation.getCurrentPosition 메서드를 사용한다.

  • 이 메서드는 사용자의 위치 정보를 가져와 lat(위도), lon(경도) 값을 location 상태에 저장한다. 이때 위치 정보 가져오기에 실패할 경우 오류 메시지를 설정한다

useEffect(() => {
  const getLocation = () => {
    if (!navigator.geolocation) {
      setError('Geolocation is not supported by your browser');
      return;
    }

    navigator.geolocation.getCurrentPosition(
      (position) => {
        setLocation({
          lat: position.coords.latitude,
          lon: position.coords.longitude,
        });
      },
      () => {
        setError('Unable to retrieve your location');
      }
    );
  };

  getLocation();
}, []);

2. 날씨 및 공기질 데이터 가져오기

  • 위치 정보가 설정되면, OpenWeatherMap API 호출하여 현재 날씨, 공기질, 3일간의 에보 데이터를 가져온다.

  • 데이터를 가져오기 위해 fetch API를 사용하며, 비동기적으로 모든 API 호출이 완료될 때 까지 기다리기 위해 Promise.all을 사용한다.

useEffect(() => {
  const fetchData = async () => {
    if (!location) return;

    try {
      const { lat, lon } = location;
      const weatherUrl = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${apiKey}&units=metric`;
      const airQualityUrl = `https://api.openweathermap.org/data/2.5/air_pollution?lat=${lat}&lon=${lon}&appid=${apiKey}`;
      const forecastUrl = `https://api.openweathermap.org/data/2.5/forecast?lat=${lat}&lon=${lon}&appid=${apiKey}&units=metric`;

      const [weatherResponse, airQualityResponse, forecastResponse] =
        await Promise.all([
          fetch(weatherUrl),
          fetch(airQualityUrl),
          fetch(forecastUrl),
        ]);

      if (
        !weatherResponse.ok ||
        !airQualityResponse.ok ||
        !forecastResponse.ok
      ) {
        throw new Error('Failed to fetch weather or air quality data');
      }

      const weatherData = await weatherResponse.json();
      const airQualityData = await airQualityResponse.json();
      const forecastData = await forecastResponse.json();

      setWeatherData(weatherData);
      setAirQualityData(airQualityData);
      setForecastData(forecastData);
      setLoading(false);
    } catch (err) {
      setError(err.message);
      setLoading(false);
    }
  };

  fetchData();
}, [location, apiKey]);
  • 이 useEffect 훅은 location과 apikey가 변경될 때 마다 실행되며, fetch 함수를 이용해서 네트워크 요청을 만들어서 데이터를 가져오는 데 사용된다.

  • 주로 RESTful API 서버와 통신하여 데이터를 가져오거나 전송하는 데 사용된다.

  • async 는 함수 앞에 붙여서 해당 함수가 비동기 작업을 수행함을 나타낸다.

  • async 함수는 항상 Promise를 반환하며 비동기 작업이 완료되면 resolve 상태의 Promise를 반환하며 오류가 발생하면 rejected 상태의 Promise를 반환한다.

  • Promise.all 을 사용해서 세 가지 데이터를 병렬로 가져온다. 병렬로 요청을 보내기 때문에, 순차적으로 요청하는 것보다 더 빠르게 데이터를 가져올 수 있다.

3. Json 데이터 파싱


const weatherData = await weatherResponse.json();
const airQualityData = await airQualityResponse.json();
const forecastData = await forecastResponse.json();
  • fetch 요청으로부터 받은 응답은 JSON 으로 파싱한다. 이 과정도 비동기이기 때문에 await 키워드를 사용하여 처리한다.

0개의 댓글