0

I have 2 problem with my setInterval.

First is, when I try to update a state from a useState, at each iteration of my setInterval, I'm getting doing a rollback into my first state then pushing the current value.

Second is, do not succeed to do a clearInterval and I'm so on an infinit loop.

Here is my code :

   const [coordinates, setCoordinates] = useState<{lat: number, lng: number}[]>([]);
   let coord = [{cp: '35001', time: 1000}, {cp: '35510', time: 2000}]
    useEffect(() => {
        let i = 0
            const interval = setInterval(() => {
                    console.log(i)
                    console.log(coordinates, 'iciiiiiiiiii')
                    geoCodeConfig()
                    Geocode.fromAddress(coord[i].cp).then(
                        response => {
                            const {lat, lng} = response.results[0].geometry.location;
                            setCoordinates([...coordinates, {lat: lat, lng: lng}]);
                        },
                        error => {
                            console.error(error);
                        }
                    )
                i++
                if(i === coord.length) { clearInterval(interval)}
            }, 2000)
    }, [])

Thank you

  • Problem is the closure of the callback function of `setInterval` over the state. See this [related question](https://stackoverflow.com/questions/65108274/setinterval-dynamic-delay-in-useeffect-causes-infinite-loop) which might give you an idea of what's causing the problem. – Yousaf Dec 04 '20 at 13:34
  • Ho. So that mean what is used inside the setInterval is like a picture of a t moment ? – Kevin Mendes Dec 04 '20 at 13:37
  • Yes, that _picture of the moment_ is a moment when the callback function of the `setInterval` was defined. What you should do is add `coordinates` in the dependency array of the `useEffect` hook so that each time state is updated, a new interval is set in your component. Also make sure that, before setting the new interval, previous interval is cleared. You can do this using the cleanup function of `useEffect` hook. – Yousaf Dec 04 '20 at 13:41
  • Have you tried passing `coordinates` to the dependency array of `useEffect`? – BlackMath Dec 04 '20 at 13:41

0 Answers0