简体   繁体   中英

Set delay for axios get request in useEffect

I am using react js, and when rendering the page a useEffect is implemented to request to express server to get data from database, this works, but if the server is down it will keep on requesting thousands of times until the app crashes. Is there a way to set a delay between every re-request? Or is there a neater solution for this?

Below is my code:

  useEffect(() => {
    async function fetchData() {
      setisLoaded(false);
      axios
        .get("localhost:3001/locations")
        .then((response) => {
          if (response.data) {
            setLocations(response.data[0]);
            setTown(response.data[1]);
            setTowns(response.data[1]);
            setDistrict(response.data[2]);
            setDistricts(response.data[2]);
            setGovernorate(response.data[3]);
            setSector(response.data[4]);
            setSubSector(response.data[5]);
            setSubSectors(response.data[5]);
            setlicenseType(response.data[6]);
            setmarkerGroup(true);
            setZoomLevel(8);
            setisLoaded(true);
          }
        })
        .catch((e) => {
          seterrorFetchedChecker((c) => !c);
        });
    }
    fetchData();
  }, [errorFetchedChecker]);

And the express code is:

app.get("/locations", async (req, res) => {
  try {
    const sqlFetch =
      "SELECT * FROM industries_db; SELECT * FROM towns ORDER BY value; SELECT * FROM districts ORDER BY value ; SELECT * FROM governorates ORDER BY value;  SELECT * FROM sectors ORDER BY value; SELECT * FROM sub_sectors ORDER BY value; SELECT * FROM licensetype ORDER BY value ";

    await db.query(sqlFetch, async (err, result) => {
      if (err) {
        console.log(err);
        res.sendStatus(500);
      } else if (result.length > 0) {
        return res.send(result);
      }
    });
  } catch (error) {
    res.sendStatus(500);
  }
});

I know my code is not as professional, I'm still new to web dev, please feel free to give any comments to make the flow better and giving me advices in coding techincs.

Thank You!

This is because every time you have an error in your request you update the state and the useEffect function get fired again and again.

You can implement a check based on the error with this logic:

if there is an error on the request, wait a predefined amount of time and fetch data, otherwise fetch data immediately:

  useEffect(() => {
    async function fetchData() {
      setisLoaded(false);
      axios
        .get("localhost:3001/locations")
        .then((response) => {
          if (response.data) {
            setLocations(response.data[0]);
            setTown(response.data[1]);
            setTowns(response.data[1]);
            setDistrict(response.data[2]);
            setDistricts(response.data[2]);
            setGovernorate(response.data[3]);
            setSector(response.data[4]);
            setSubSector(response.data[5]);
            setSubSectors(response.data[5]);
            setlicenseType(response.data[6]);
            setmarkerGroup(true);
            setZoomLevel(8);
            setisLoaded(true);
          }
        })
        .catch((e) => {
          seterrorFetchedChecker((c) => !c);
        });
    }
    
    if(errorFetchedChecker){
        setTimeout(()=>{
            fetchData();
        },[1000])// 1 second
    } else {
        fetchData();
    }    
  }, [errorFetchedChecker]);

Another solution is to use axios retry policy and avoid to update the state with the error if there was an error yet, but the first solution is good enough.

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