local-weather/components/WeatherNow.tsx
ChrQR a21c44185f added weather to context provided by weatherNow.
The application structure and naming should take in to account the weathernow component will be the container
2024-05-10 01:10:37 +02:00

43 lines
1.2 KiB
TypeScript

"use client";
import { getHourlyForecast } from "@/app/actions";
import Temperature from "./Temperature";
import { HourlyForecast, WeatherContextType} from "@/types/types";
import { createContext, useContext, useEffect, useState } from "react";
import { defaultHourlyForecast } from "@/app/defaultState";
import { LocationContext } from "@/app/page";
export const WeatherContext = createContext<WeatherContextType>({
weather: defaultHourlyForecast,
setWeather: () => {} // Default function, does nothing
});
export default function WeatherNow() {
const { geoLocation } = useContext(LocationContext)
const [weather, setWeather] = useState<HourlyForecast>(defaultHourlyForecast);
const contextValue: WeatherContextType = {
weather,
setWeather
};
useEffect(() => {
let mounted = true;
getHourlyForecast(geoLocation).then((data) => {
if (mounted) {
setWeather(data);
}
});
return () => {
mounted = false;
};
}, [geoLocation]);
return (
<>
<h1>Here is the current weather in {geoLocation.name}</h1>
<WeatherContext.Provider value={contextValue}>
<Temperature />
</WeatherContext.Provider>
</>
);
}