vue api 파일 분리

채윤·2022년 6월 28일
0

  • weatherInfo파일에 해당하는 데이터 값들이 불러와지지 않는 현상이 발생하였다. api의 파일을 나누면서 코드의 문제가 생긴것!
  • 두군데서 다 async await를 사용해 try, catch를 해주고 있었다. 이러한 문제점을 해결하기 위해 api url이 들어있는 파일에서는 요청한 url을 리턴해주고, store의 actions에서는 try, catch를 사용해 데이터 값을 사용해 newWeatherData의 값을 업데이트 하게끔 구현 해주었다.

api/index.ts

import axios, { AxiosPromise } from "axios";

const config = {
  baseUrl: "https://api.openweathermap.org",
};

const API_KEY = process.env.VUE_APP_OPEN_API_KEY;

async function fetchWeatherData(location) {
  return await axios.get(
    `${config.baseUrl}/data/2.5/weather?q=${location}&units=metric&APPID=${API_KEY}`
  );
}

export { fetchWeatherData };

처음에 try catch를 사용하고 데이터를 리턴을 해주었는데, 요청한 데이터 URL을 리턴 해주어야 한다.

store.ts

    async fetchWeatherData({ commit }, location) {
      try {
        const { data } = await fetchWeatherData(location);
        const newWeatherData = {
          name: data.name,
          temp: data.main.temp,
          tempMin: data.main.temp_min,
          tempMax: data.main.temp_max,
          feelsLike: data.main.feels_like,
          description: data.weather[0].description,
          icon: `https://openweathermap.org/img/w/${data.weather[0].icon}.png`,
          info: data.weather[0].main,
          wind: data.wind.speed,
          humidity: data.main.humidity,
          clouds: data.clouds.all,
          country: data.sys.country,
        };
        commit("SET_WEATHER_DATA", newWeatherData);
      } catch (error) {
        console.log(error);
      }
    },

그다음 store파일에서는 async, await를 사용해서 데이터 값들이 location 값에 따라 데이터가 업데이트 되게 된다.

profile
프론트엔드 개발자

0개의 댓글