local-weather/components/WeatherNow.tsx

72 lines
2.2 KiB
TypeScript
Raw Normal View History

"use client";
2024-05-04 21:04:30 +00:00
import Temperature from "./Temperature";
2024-05-17 23:50:05 +00:00
import { Forecast, WeatherContextType, coordType } from "@/types/types";
import { createContext, useContext, useEffect, useState } from "react";
import { defaultHourlyForecast } from "@/app/defaultState";
import { LocationContext } from "@/context/LocationContext";
import WeatherHero from "./WeatherHero";
2024-05-12 19:14:36 +00:00
import CardContainer from "./DailyCard/CardContainer";
2024-05-04 21:04:30 +00:00
export const WeatherContext = createContext<WeatherContextType>({
weather: defaultHourlyForecast,
setWeather: () => {}, // Default function, does nothing
});
export default function WeatherNow() {
const { geoLocation } = useContext(LocationContext);
2024-05-12 05:06:44 +00:00
const [weather, setWeather] = useState<Forecast>(defaultHourlyForecast);
2024-05-17 23:50:05 +00:00
const [error, setError] = useState<string | null>(null);
const contextValue: WeatherContextType = {
weather,
setWeather,
};
2024-05-10 17:23:02 +00:00
2024-05-17 23:50:05 +00:00
const getHourlyForecast = async (geoLocation: coordType) => {
const { geo } = geoLocation;
try {
const response = await fetch(
`/api/forecast?lat=${geo.lat}&lng=${geo.lng}`
);
if (!response.ok) {
throw new Error("Failed to fetch the weather data");
}
const data = await response.json();
setWeather(data.data);
return data.data; // Ensure the function returns the data
} catch (error: any) {
setError(error.message);
return null;
}
};
useEffect(() => {
let mounted = true;
2024-05-17 23:50:05 +00:00
if (geoLocation.geo.lat && geoLocation.geo.lng) {
getHourlyForecast(geoLocation).then((data) => {
if (mounted && data) {
setWeather(data);
}
});
}
return () => {
mounted = false;
};
}, [geoLocation]);
2024-05-17 23:50:05 +00:00
2024-05-04 21:04:30 +00:00
return (
<div className="text-center">
<h1 className="my-4 text-2xl">
2024-05-12 05:15:21 +00:00
Here is the weather today in {geoLocation.name}
</h1>
2024-05-17 23:50:05 +00:00
{error && <p className="text-red-500">{error}</p>}
<WeatherContext.Provider value={contextValue}>
<WeatherHero />
<Temperature />
2024-05-12 19:14:36 +00:00
<h2 className="mt-2 text-xl">And the forecast for the coming week</h2>
<CardContainer weather={weather} />
</WeatherContext.Provider>
</div>
2024-05-04 21:04:30 +00:00
);
}