Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

206
Views
Ignore previous asynchronous call and execute the latest

I'm using React,

I have a button that calls an asynchronous function on every onClick event:

<MyButton onClick={handleClick}>
  Next
</MyButton>

Then a function that takes time to load data:

const isExecuting = useRef(false);

const handleClick = async () => {
  if (!isExecuting.current) {
    isExecuting.current = true;
    try {
      resetViews();
      await chargeViews(patientId);
    } finally {
      isExecuting.current = false;
    }
  }
};

So for example when I click 5 times, it will receive 5 calls and all of them will be executed in order, I need a way to just execute the latest call and ignore the previous 4 calls, so it won't take time to execute all of them.

PS: I thought of disabling the button until the function finishes executing, but as I'm using the button to load the next patient, this won't be convinient because we'd be obliged to wait for 4 patients to be loaded to load the 5th patient.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Debounce is one option and the option is to pass ref and get it cancelToken when you are trying to hit again the same API it will cancel the previous call If exist and call the new API request the below example is the general solution or you can send cancelToken from component and call it before the new API call

// dummy Api
const chargeViews = async (sourceRef,patientId) => {
  console.log({patientId})
  try {
    let token = undefined;
    if (sourceRef) {
      const CancelToken = axios.CancelToken;
      const source = CancelToken.source();
      token = { cancelToken: source.token };
      sourceRef.current = source;
    }
    const response = await Axios.get(`endpointURL`, token)
    return response.data;
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
  } catch (err: any) {
    throw new Error(err);
  }
};

component

const sourceRef = React.useRef(null);

const handleClick = async () => {
    try {
      if (sourceRef.current) sourceRef.current.cancel();
      await chargeViews(sourceRef, patientId);
    } catch (error) {
      console.log(error)
    }
};

<MyButton onClick={handleClick}>
  Next
</MyButton>
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!