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 값에 따라 데이터가 업데이트 되게 된다.