State inside loop that is running inside async function doesn't change

46 views Asked by At

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

0

There are 0 answers