0

I am having a problem that the post request is not sending the updated currentVideo state as setState seems to be nonblocking. How can i make axios wait for the state to be set?

const nextVideo = () => {
    if (videoList.indexOf(currentVideo) < videoList.length - 1) {
      setCurrentVideo(videoList[videoList.indexOf(currentVideo) + 1]);
      setLoading(true);
      axios
        .post(`${BACK_PORT}/videos/download`, currentVideo)
        .then(function (response) {
          if (response.data) {
            setLoading(false);
          } else {
            console.log("waiting...");
          }
        })
        .catch(function (error) {
          alert(error)
        });
    } else {
      alert("This is the last video");
    }
  };
coolps811
  • 193
  • 4
  • 11
  • 1
    Setting state is fully asynchronous, have you looked into using an [effect](https://reactjs.org/docs/hooks-effect.html) on the `currentVideo` state? – DBS Mar 22 '21 at 14:41
  • Does this answer your question? [useState set method not reflecting change immediately](https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately) – Emile Bergeron Mar 22 '21 at 15:04

1 Answers1

1

Use a variable and store the currentvideo value in it. Then use that variable at both the places,i.e., for setting up the state and making the axios call.

const nextVideo = () => {
    if (videoList.indexOf(currentVideo) < videoList.length - 1) {
      let currentVideo = videoList[videoList.indexOf(currentVideo) + 1] //change here
      setCurrentVideo(currentVideo );
      setLoading(true);
      axios
        .post(`${BACK_PORT}/videos/download`, currentVideo)
        .then(function (response) {
          if (response.data) {
            setLoading(false);
          } else {
            console.log("waiting...");
          }
        })
        .catch(function (error) {
          alert(error)
        });
    } else {
      alert("This is the last video");
    }
};
Rohan Agarwal
  • 2,441
  • 2
  • 18
  • 35