Files
weather-app/frontend/src/utils/apiFunc.ts

29 lines
918 B
TypeScript

import { myToast } from "./toastify";
export const fetchWeather = async (
city: string,
apiKey: string,
units: string
) => {
// Get location data
const location = await fetch(
`http://api.openweathermap.org/geo/1.0/direct?q=${city}&appid=${apiKey}`
).then((response) => {
if (response.status === 401) {
myToast("You are not authorized to access this resource. Please check your API key.", "error");
} else if (response.ok) {
return response.json();
} else {
myToast("Error fetching location data: " + response.statusText, "error");
}
});
const lat = location[0].lat;
const lon = location[0].lon;
// Get weather data
const weather = await fetch(
`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${apiKey}&units=${units}`
).then((response) => response.json());
localStorage.setItem("weather", JSON.stringify(weather));
};