0

I have two functions one function to fetch data using API inside the loop and a second function that changes a state cancel from false to true. But that state doesn't update inside that loop hence I cannot stop the API call.

Below is the template code

const [cancel, setCancel] = useState(false);
const cancelFtn = ()=>{
setCancel(true)
}
const fetchData = async ()=>{
for (let i = 0; i < data.length; i++) {
          const res = await fetch(putObjectSignedUrl, {
          method: "PUT",
          body: files[i],
          headers: {
            "Content-Type": "application/json",
          },
        });
 if (res) {
//cancel state doesn't change here if in between iteration of loop I have called cancelFtn function on click of some button
          if (!cancel) {
            await fetchInvoiceData(key);
          } else {
            console.log("Cancelled");
          }
   }
}

I want an updated state inside the loop. I have tried to use effect too but it also didn't work

Syed
  • 1
  • 1
    The issue seems to be with the calling of the `cancelFtn` function the js is busy executing the for loop and will do other things after the loop ends. – Ankit Apr 19 '23 at 06:48
  • Please trim your code to make it easier to find your problem. Follow these guidelines to create a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). – Community Apr 19 '23 at 07:32
  • I think that with this case it is better to use a ref for your cancel – OneQ Apr 23 '23 at 08:38

0 Answers0