I have an app that upon the user loading it, uses Javascript's built-in API to fetch geolocation data. Then, it passes this data along to a component that is supposed to use this in an API call to OpenWeather. However, the API call is happening well before the Geolocation can load. I have tried making my useLocation function asynchronous to await (success) but it did not work.
Here is the code to my App.js
const useLocation = () => {
const [location, setLocation] = useState({lat: 0, long: 0})
useEffect(()=>{
const success = (position) =>{
let lat = position.coords.latitude
let long = position.coords.longitude
console.log(lat, long)
setLocation({lat: lat, long: long})
}
navigator.geolocation.getCurrentPosition(success)
},[])
return location;
}
function App() {
// Gets just the
const location = useLocation()
function App() {
// Gets just the
const location = useLocation()
const routes = ['nasa','openweather','zomato']
return (
<div className="App">
<Route exact path="/openweather">
<Weather position={location} />
</Route>
</div>
}
Here is the code for Weather.js
import { useState, useEffect } from "react"
const Weather = ({ position }) => {
const long = position.long
const lati = position.lat
const APIKey = '1234'
const [weather, setWeather] = useState()
const initData = async () => {
const response = await fetch(`https://api.openweathermap.org/data/2.5/weather?lat=${lati}&lon=${long}&appid=${APIKey}`)
const weatherData = await response.json()
setWeather(weatherData)
console.log(response)
}
useEffect(()=> {
initData()
},[])