简体   繁体   中英

Stop infinite loop in react native useEffect

I am calling one function through setInterval but function go to infinite loop and my applicaiton get stuck. It's happen it on android, Could someone please help me how to resolve this issue.

Thanks

  useEffect(() => {
    const interval = setInterval(() => {
      sendCoordinate(location);
    }, 180000);

    return () => clearInterval(interval);
  }, [location]);

A function that I am calling

const sendCoordinate = async (locParms) => {
    console.log("@2 it working3", checkDayStatus, location);
    if (checkDayStatus === "Started") {
      let data = {
        lat:
          locParms !== null
            ? locParms && locParms.lat
            : location && location.lat,
        lng:
          locParms !== null
            ? locParms && locParms.lng
            : location && location.lng,
        dispatcher_id: 1,
        truck_id: 1,
      };

      return await LocationAPI.sendLocationFeed(data);
    }
  };

It turns out that your timer is created every time, just leave the useEffect arguments empty, [location] -> []

useEffect(() => {
  const interval = setInterval(() => {
    sendCoordinate(location);
  }, 180000);

  return () => clearInterval(interval);
}, [location.lng, location.lat]);

So you need to change the location from the dependency array like this.

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