-1

im working on a tracking application that starts the set interval which gets the geolocation every 5 seconds after clicking the start button. the start button sets the tracking state to true which starts the set interval in the first place. I'm trying to stop the set interval when I click on the end button by setting the track state to false but the set interval keeps on going even if the track state turns to false

my component

        <button id="start" onClick={() => setTrackState(true)}>
           Start
        </button>
        <button id="end" onClick={() => setTrackState(false)}>
           End
        </button>

my hook

useEffect(() => {
  console.log("track useEffect");
  console.log(`trackState is ${trackState}`);
  if (trackState) {
     const interval = setInterval(() => {
        console.log("the interval is running");
        navigator.geolocation.getCurrentPosition(
           onSuccess,
           onError,
           options
        );
     }, 5000);
  } else {
     console.log("the interval is not running");
     clearInterval();
  }
}, [trackState, setTrackState]);
GODMAN
  • 11
  • 2
  • 1
    You need to call `clearInterval(interval)`. An empty parameter list does nothing because it doesn't know which interval to clear. Why is `setTrackState` in the `useEffect` capture list? – ggorlen Apr 19 '22 at 15:09
  • [`clearInterval(intervalID)`](https://developer.mozilla.org/en-US/docs/Web/API/clearInterval): _"`intervalID`: The identifier of the repeated action you want to cancel. This ID was returned by the corresponding call to `setInterval()`"_ – Andreas Apr 19 '22 at 15:09
  • Also why do you try to re-invent [`.watchPosition()`](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/watchPosition)? – Andreas Apr 19 '22 at 15:11
  • @Andreas because I'm trying to log the location to a database – GODMAN Apr 19 '22 at 15:43

1 Answers1

0

I could solve the problem by the following approach. I am new to react and I didn't know I had to clear the setInterval twice when using the setInterval function

useEffect(() => {
  let interval = null;
  console.log("track useEffect");
  console.log(`trackState is ${trackState}`);
  if (trackState) {
     interval = setInterval(() => {
        console.log("the interval is running");
        navigator.geolocation.getCurrentPosition(
           onSuccess,
           onError,
           options
        );
     }, 5000);
  } else {
     console.log("the interval is not running");
     clearInterval(interval);
  }
  return () => clearInterval(interval);
}, [trackState]);
RusJaI
  • 666
  • 1
  • 7
  • 28
GODMAN
  • 11
  • 2