简体   繁体   中英

React axios triggers bunch get requests

I have a server and a route('/is-working') in which I render simply Yes or No, in React I do a get request with Axios every second with the use of intervals to see if its working.
Here is the code:

useEffect(() => {
    const interval = setInterval(async () => {
        await axios.get('http://192.168.1.57/is-working')
        .then(res => {
          if (res?.status === 200) {
             // Do somthing
          }
        })
        .catch(err => {
          return Promise.reject(err);
        })
    }, 1000);
    return () => clearInterval(interval);
  }, []);

I want to count the number of times I get a 200 response back, when I stop hosting http://192.168.1.57/is-working and it returns an network error, until now everything is fine, but when I start hosting http://192.168.1.57/is-working again it does a bunch of get requests all together. It seems its requesting all of the ones that returned network error again.
thanks for the help in advance.

That must be because you didn't defined a timeout for axios client. So, it still trying to request your endpoint, once it comes back it does all request at once Take a look here: https://github.com/axios/axios#axioscreateconfig

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM