feat: implement weather fetching API and update frontend components for improved user experience

This commit is contained in:
2025-08-03 19:10:20 +02:00
parent b6b6146ad0
commit 43262846a5
8 changed files with 140 additions and 77 deletions

View File

@@ -1,36 +1,30 @@
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(
`https://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"
);
export const fetchWeather = async (city: string, units: string) => {
try {
const response = await fetch(
`http://localhost:7001/api/fetchWeather?city=${encodeURIComponent(
city
)}&units=${encodeURIComponent(units)}`,
{
method: "GET",
headers: {
"Content-Type": "application/json",
},
}
} 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));
const responseData = await response.json();
if (!response.ok) {
myToast(responseData.error, "error");
return;
}
localStorage.setItem("weather", JSON.stringify(responseData.data));
return;
} catch (error) {
const errorMsg = JSON.stringify(error);
myToast(errorMsg, "error");
return null;
}
};