local-weather/components/WeatherNow.tsx

62 lines
1.9 KiB
TypeScript
Raw Normal View History

"use client";
2024-05-04 21:04:30 +00:00
import { getHourlyForecast } from "@/app/actions";
import Temperature from "./Temperature";
2024-05-12 05:06:44 +00:00
import { Forecast, WeatherContextType } 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 05:06:44 +00:00
import DailyCard from "./DailyCard/DailyCard";
2024-05-04 21:04:30 +00:00
export const WeatherContext = createContext<WeatherContextType>({
weather: defaultHourlyForecast,
setWeather: () => {}, // Default function, does nothing
});
2024-05-10 17:23:02 +00:00
export default function WeatherNow() {
const { geoLocation } = useContext(LocationContext);
2024-05-12 05:06:44 +00:00
const [weather, setWeather] = useState<Forecast>(defaultHourlyForecast);
const contextValue: WeatherContextType = {
weather,
setWeather,
};
2024-05-10 17:23:02 +00:00
useEffect(() => {
let mounted = true;
getHourlyForecast(geoLocation).then((data) => {
if (mounted) {
setWeather(data);
}
});
return () => {
mounted = false;
};
}, [geoLocation]);
2024-05-04 21:04:30 +00:00
return (
<div className="text-center">
<h1 className="my-4 text-2xl">
2024-05-12 05:06:44 +00:00
Here is the current weather today in {geoLocation.name}
</h1>
<WeatherContext.Provider value={contextValue}>
<WeatherHero />
<Temperature />
2024-05-12 05:06:44 +00:00
<h2 className="mt-4 text-xl">And the forecast for the coming week</h2>
<div className="flex h-full">
{weather.daily && weather.daily.apparent_temperature_max.map((temp, index) => (
index > 0 &&
index < 7 && // Ensure we only render the next 6 days
<DailyCard
2024-05-10 17:23:02 +00:00
key={index}
temperature={temp}
2024-05-12 05:06:44 +00:00
weatherCode={weather.daily.weather_code[index]}
time={weather.daily.time[index]}
2024-05-10 17:23:02 +00:00
/>
))}
</div>
</WeatherContext.Provider>
</div>
2024-05-04 21:04:30 +00:00
);
}