npereznyc / Project-2-Weather-App

0 stars 1 forks source link

Glow: Geolocation #23

Open npereznyc opened 1 year ago

npereznyc commented 1 year ago

The feature that has the most impact on our project’s functionality is the use of geolocation, as it allows the user to get their weather data without needing to input anything. It was also quite challenging to figure out getting it to work with our API, so we are proud of it.

function getLocation(){

        navigator.geolocation.getCurrentPosition(function(position) {
          setLat(position.coords.latitude)
          setLong(position.coords.longitude)
        })
      }
      async function getData() {
        const url=`https://api.open-meteo.com/v1/forecast?latitude=${lat}&longitude=${long}&hourly=apparent_temperature&daily=weathercode,temperature_2m_max,temperature_2m_min,sunrise,sunset,rain_sum,windspeed_10m_max,winddirection_10m_dominant&current_weather=true&temperature_unit=fahrenheit&windspeed_unit=mph&precipitation_unit=inch&timezone=auto`
        try{
          const response = await fetch (url)
          const data = await response.json()
          setTempData(data)
        }catch(err){
          setError(err)
        }
      }
    useEffect(()=> {
        getLocation()
    }, [])

    useEffect(()=> {
      if(lat && long) {
        getData()
      }
    }, [lat, long])

  return (
      tempData
      ?
      <div className="App">
        {error && <h1 className="Error">Could not load your weather data.</h1>}
        <Routes>
          <Route path="/" element={<><Sidebar weatherData={tempData}/> <Wind weatherData={tempData}/> <SunriseSunset weatherData={tempData}/> <WeeklyForecast weatherData={tempData}/></>} />
          <Route path="/weekly" element= {<ExtendedCast weatherData={tempData}/>} />
        </Routes>
      </div> 
      : <p>Loading...</p>
    );
  }

  export default App
Rancor38 commented 1 year ago

This fetch combined with the dual-state of lat/long is delightful to look at. A very clever implementation of the tools in front of you both. The use of conditional rendering is also a plus, as well as leveraging the bracketed content within useEffect. It really shows off your understanding of these tools.