11import { useState , useEffect } from "react" ;
22
33export default function WeatherWidget ( ) {
4- interface Weather {
5- temperature : number ;
6- windspeed : number ;
7- }
8-
9- const [ weather , setWeather ] = useState < Weather | null > ( null ) ;
10- const [ city ] = useState ( "New York" ) ;
4+ const [ weather , setWeather ] = useState < WeatherData | null > ( null ) ;
5+ const [ location , setLocation ] = useState < {
6+ latitude : number | null ;
7+ longitude : number | null ;
8+ } > ( {
9+ latitude : null ,
10+ longitude : null ,
11+ } ) ;
1112 const [ error , setError ] = useState ( "" ) ;
1213
1314 useEffect ( ( ) => {
14- fetchWeather ( ) ;
15+ if ( navigator . geolocation ) {
16+ navigator . geolocation . getCurrentPosition (
17+ ( position ) => {
18+ setLocation ( {
19+ latitude : position . coords . latitude ,
20+ longitude : position . coords . longitude ,
21+ } ) ;
22+ } ,
23+ ( ) => {
24+ setError ( "Unable to retrieve your location." ) ;
25+ }
26+ ) ;
27+ } else {
28+ setError ( "Geolocation is not supported by your browser." ) ;
29+ }
1530 } , [ ] ) ;
1631
17- const fetchWeather = async ( ) => {
32+ useEffect ( ( ) => {
33+ if ( location . latitude && location . longitude ) {
34+ fetchWeather ( location . latitude , location . longitude ) ;
35+ }
36+ } , [ location ] ) ;
37+
38+ interface WeatherData {
39+ temperature : number ;
40+ windspeed : number ;
41+ }
42+
43+ const fetchWeather = async (
44+ latitude : number ,
45+ longitude : number
46+ ) : Promise < void > => {
1847 try {
1948 const response = await fetch (
20- `https://api.open-meteo.com/v1/forecast?latitude=40.7128 &longitude=-74.0060 ¤t_weather=true`
49+ `https://api.open-meteo.com/v1/forecast?latitude=${ latitude } &longitude=${ longitude } ¤t_weather=true`
2150 ) ;
2251 if ( ! response . ok ) throw new Error ( "Failed to fetch weather data" ) ;
23- const data = await response . json ( ) ;
52+ const data : { current_weather : WeatherData } = await response . json ( ) ;
2453 setWeather ( data . current_weather ) ;
25- } catch {
54+ } catch ( err ) {
55+ console . error ( err ) ;
2656 setError ( "Unable to fetch weather data." ) ;
2757 }
2858 } ;
@@ -31,7 +61,7 @@ export default function WeatherWidget() {
3161 < div
3262 style = { { border : "1px solid #ccc" , padding : "10px" , borderRadius : "8px" } }
3363 >
34- < h3 > Weather in { city } </ h3 >
64+ < h3 > Current Weather </ h3 >
3565 { error && < p style = { { color : "red" } } > { error } </ p > }
3666 { weather ? (
3767 < div >
0 commit comments