I'm fairly new to react and decided to develop a simple weather app.Once the page loads I want the app to ask the user for geoloacaion and then display weather data accordingly.
function App() {
const [weather, setWeather] = useState(null);
useEffect(() => {
navigator.geolocation.getCurrentPosition(async (position) => {
let { latitude, longitude } = position.coords;
const data = await getWeatherByCords(latitude, longitude);
await setWeather(data); // Line 8
console.log(weather) //outputs undefined
setWeather('hhello'); // Line 10
console.log(weather) //outputs undefined
let address = await cordsToAddress(latitude, longitude);
});
},[]);
return (
<div className="App">
<h3>Weather App</h3>
<Weather
data={weather.data}
/>
</div>
);
}
export default App;
getWeatherByCords()
is just a helper function which sends the request to a weather api and returns its response
I read that useEffect(() => {},[])
hook is equal to componentDidMount()
, and as far as I understand is should trigger only when the page is loaded or refreshed, please correct me if I'm wrong
When I try to set weather
do the data I received or just for a test to some string,to pass it in the <Weather/>
components afterwards, it doesn't work in both cases for some reason and when I try to log weather
in console I get undefined in both cases.
Also should I await setting weather(as in line 8) or should I not(as in line 10)?