"use client"; import Temperature from "./Temperature"; 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"; import CardContainer from "./DailyCard/CardContainer"; export const WeatherContext = createContext({ weather: defaultHourlyForecast, setWeather: () => {}, // Default function, does nothing }); export default function WeatherNow() { const { geoLocation } = useContext(LocationContext); const [weather, setWeather] = useState(defaultHourlyForecast); const [error, setError] = useState(null); const contextValue: WeatherContextType = { weather, setWeather, }; 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; if (geoLocation.geo.lat && geoLocation.geo.lng) { getHourlyForecast(geoLocation).then((data) => { if (mounted && data) { setWeather(data); } }); } return () => { mounted = false; }; }, [geoLocation]); return (

Here is the weather today in {geoLocation.name}

{error &&

{error}

}

And the forecast for the coming week

); }