import { myToast } from "./toastify"; import Cookies from "js-cookie"; 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) { if (Cookies.get("apiKey") === undefined || Cookies.get("apiKey") === "") { myToast("You have to enter an API key!", "error"); } else { myToast( "You are not authorized to access this resource. Please check your API key. (Error: x4010)", "error" ); } } else if (response.ok) { return response.json(); } else { myToast("Error fetching location data. (Error: x32)", "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)); };