Skip to content
Advertisement

Why is this function behaving differently on calling first time and second time in React js?

I am trying to implement a turn by turn navigation with mapbox gl js in react,I am trying to make the marker positon update smooth instead of it being teleported.So to perform the animation I am trying to call a function recursively but for some reason the same function behaves differently when called second time compared to the first,code snippet is given below (logs)

const animateMarker = () => {
  setSteps(0);
  const lng = endlongitude - longitude;
  const lat = endlatitude - latitude;
  setDeltaLng(lng / numDeltas);
  setDeltaLat(lat / numDeltas);

  makeAnimation();
};


const makeAnimation = () => {
  let t = 0;

  setLatitude(latitude + deltaLat);
  setLongitude(longitude + deltaLng);
  let lat = 13.0547712;
  let lng = 80.1144832;

  const loop = () => {
    setTimeout(() => {
      lng = lng + deltaLng;
      lat = lat + deltaLat;
      console.log(lat);
      t++;
      usermarker ? .setLngLat([lng + deltaLng, lat + deltaLat]);
      if (t != numDeltas) {
        loop();
      }
    }, 100);
  };
  loop();
};



<!-- end snippet -

<!-- begin snippet: js hide: false console: true babel: false -->

> I am using normal JS variables instead of react useState because useState doesnt work in 
recursive state updation.This behaviour is very weird ,also I have attached the console log for the variable showing both functions running but behaving differently
 <button
        className="nav-btn"
        onClick={(e) => {
          animateMarker();
        }}
      >
        navigate
      </button>

->

`

Advertisement

Answer

Your function makeAnimation captured the value of the state values when you first called it, so it won’t update the delta variables.

Consider using the functional form of the setState hook.

Advertisement