local-weather/components/WeatherNow.tsx
christian e52b362512
Some checks failed
Docker Build & Publish / Build Docker (push) Failing after 52s
changed to weekly from hourly
2024-05-12 07:06:44 +02:00

62 lines
1.9 KiB
TypeScript

"use client";
import { getHourlyForecast } from "@/app/actions";
import Temperature from "./Temperature";
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";
import DailyCard from "./DailyCard/DailyCard";
export const WeatherContext = createContext<WeatherContextType>({
weather: defaultHourlyForecast,
setWeather: () => {}, // Default function, does nothing
});
export default function WeatherNow() {
const { geoLocation } = useContext(LocationContext);
const [weather, setWeather] = useState<Forecast>(defaultHourlyForecast);
const contextValue: WeatherContextType = {
weather,
setWeather,
};
useEffect(() => {
let mounted = true;
getHourlyForecast(geoLocation).then((data) => {
if (mounted) {
setWeather(data);
}
});
return () => {
mounted = false;
};
}, [geoLocation]);
return (
<div className="text-center">
<h1 className="my-4 text-2xl">
Here is the current weather today in {geoLocation.name}
</h1>
<WeatherContext.Provider value={contextValue}>
<WeatherHero />
<Temperature />
<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
key={index}
temperature={temp}
weatherCode={weather.daily.weather_code[index]}
time={weather.daily.time[index]}
/>
))}
</div>
</WeatherContext.Provider>
</div>
);
}