11"use client" ;
22import { useState , useEffect } from "react" ;
3+ import { WeatherFetchStatus } from "./enum" ;
34
45export default function WeatherWidget ( ) {
56 const [ weather , setWeather ] = useState < WeatherData | null > ( null ) ;
@@ -11,6 +12,9 @@ export default function WeatherWidget() {
1112 longitude : null ,
1213 } ) ;
1314 const [ error , setError ] = useState ( "" ) ;
15+ const [ status , setStatus ] = useState < WeatherFetchStatus > (
16+ WeatherFetchStatus . Idle
17+ ) ;
1418
1519 useEffect ( ( ) => {
1620 if ( navigator . geolocation ) {
@@ -23,10 +27,12 @@ export default function WeatherWidget() {
2327 } ,
2428 ( ) => {
2529 setError ( "Unable to retrieve your location." ) ;
30+ setStatus ( WeatherFetchStatus . Error ) ;
2631 }
2732 ) ;
2833 } else {
2934 setError ( "Geolocation is not supported by your browser." ) ;
35+ setStatus ( WeatherFetchStatus . Error ) ;
3036 }
3137 } , [ ] ) ;
3238
@@ -45,16 +51,19 @@ export default function WeatherWidget() {
4551 latitude : number ,
4652 longitude : number
4753 ) : Promise < void > => {
54+ setStatus ( WeatherFetchStatus . Loading ) ;
4855 try {
4956 const response = await fetch (
5057 `https://api.open-meteo.com/v1/forecast?latitude=${ latitude } &longitude=${ longitude } ¤t_weather=true`
5158 ) ;
5259 if ( ! response . ok ) throw new Error ( "Failed to fetch weather data" ) ;
5360 const data : { current_weather : WeatherData } = await response . json ( ) ;
5461 setWeather ( data . current_weather ) ;
62+ setStatus ( WeatherFetchStatus . Success ) ;
5563 } catch ( err ) {
5664 console . error ( err ) ;
5765 setError ( "Unable to fetch weather data." ) ;
66+ setStatus ( WeatherFetchStatus . Error ) ;
5867 }
5968 } ;
6069
@@ -64,13 +73,15 @@ export default function WeatherWidget() {
6473 >
6574 < h3 > Current Weather</ h3 >
6675 { error && < p style = { { color : "red" } } > { error } </ p > }
67- { weather ? (
76+ { status === WeatherFetchStatus . Loading && < p > Loading...</ p > }
77+ { status === WeatherFetchStatus . Success && weather && (
6878 < div >
6979 < p > Temperature: { weather . temperature } °C</ p >
7080 < p > Wind Speed: { weather . windspeed } km/h</ p >
7181 </ div >
72- ) : (
73- < p > Loading...</ p >
82+ ) }
83+ { status === WeatherFetchStatus . Error && ! weather && (
84+ < p > Failed to load weather.</ p >
7485 ) }
7586 </ div >
7687 ) ;
0 commit comments