0

I'm new to react and I'm trying to build a Weather App for my project. It keeps sending the request to the API I'm using which is OpenWeatherMap API. I'm using Axios to send the request.

Here's what my code looks like:

import React, {useEffect, useState} from 'react';  
import axios from 'axios';

const App = () => {
  const [ data, setData ] = useState(null);
  const APIKEY = <APIKEY>;

  useEffect(()=>{
    window.navigator.geolocation.getCurrentPosition(
      async position=>{
        await axios.get(`https://api.openweathermap.org/data/2.5/onecall?lat=${position.coords.latitude}&lon=${position.coords.longitude}&appid=${APIKEY}`)
        .then(response=>{
          setData(response.data);
        }).catch(error=>{
          console.log(error);
        })
      }
    )
  }, []);
  
  console.log(data);
  return<div>hello</div>
}


export default App;

I tried using class components it doesn't work either way.

  • Sounds like expected behaviour if the `window.navigator.geolocation.watchPosition` is triggered it will send a request, right? – Julian Kleine Jan 05 '21 at 23:27
  • btw how do you know it keeps sending the requests? if it's because of the `console.log(data)` that will be logged everytime the component function is executed, that doesn't mean the data changed, if you only want logs because something changed then wrap it with useEffect – Julian Kleine Jan 05 '21 at 23:31
  • I treied making it getCurrentPosition but it still does the same – Ansh Bhatia Jan 05 '21 at 23:45
  • how do you know it keeps sending the requests? – Julian Kleine Jan 05 '21 at 23:48
  • Through the network tab in chrome developer tools, it keeps calling the API and it further keeps console.logging the data repeatedly. – Ansh Bhatia Jan 05 '21 at 23:49
  • I mean that data is repeatedly logged I just explained. That doesn't mean data changed. That it is in the network tab is weird to be honest, I made a little test and couldn't reproduce it. Can you make a little codesandbox or something? – Julian Kleine Jan 05 '21 at 23:51
  • Here you go: https://codesandbox.io/s/jolly-taussig-zg4o0?file=/src/App.js See how it sends multiple requests. I've figured that it's because geolocation keeps triggering and i tried controlling it through if else but it didn't stop. – Ansh Bhatia Jan 06 '21 at 00:03
  • The codesandbox seems emtpy/default to me. This only gives one log for me. Not multiple ones. https://codesandbox.io/s/cocky-moon-s2u7r?file=/src/App.js – Julian Kleine Jan 06 '21 at 00:08
  • Hey thanks! It got better, it doesn't ruthlessly send an infinite amount of requests now but it still sends multiple requests, check your codesandbox link once. I updated the code there. – Ansh Bhatia Jan 06 '21 at 00:28
  • is your issue fixed? – Ketan Ramteke Jan 06 '21 at 00:58
  • No it keeps sending requests again when I try to return or log the data – Ansh Bhatia Jan 06 '21 at 01:47

0 Answers0