local-weather/components/WeatherNow.tsx

60 lines
1.8 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-10 17:23:02 +00:00
import { HourlyCardPropType, HourlyForecast, WeatherContextType } from "@/types/types";
import { createContext, useContext, useEffect, useState } from "react";
import { defaultHourlyForecast } from "@/app/defaultState";
import { LocationContext } from "@/app/page";
import WeatherHero from "./WeatherHero";
2024-05-10 17:23:02 +00:00
import HourlyCard from "./HourlyCard/HourlyCard";
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);
const [weather, setWeather] = useState<HourlyForecast>(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">
Here is the current weather in {geoLocation.name}
</h1>
<WeatherContext.Provider value={contextValue}>
<WeatherHero />
<Temperature />
2024-05-10 17:23:02 +00:00
<div className="flex flex-wrap h-full">
{weather.hourly && weather.hourly.apparent_temperature.map((temp, index) => (
index < 12 && // Ensure we only render the first 12 hours
<HourlyCard
key={index}
temperature={temp}
weatherCode={weather.hourly.weather_code[index]}
time={weather.hourly.time[index]}
2024-05-10 17:23:02 +00:00
/>
))}
</div>
</WeatherContext.Provider>
</div>
2024-05-04 21:04:30 +00:00
);
}