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

197
Views
Ignorar la llamada asíncrona anterior y ejecutar la última

Estoy usando Reaccionar,

Tengo un botón que llama a una función asíncrona en cada evento onClick:

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

Luego una función que tarda en cargar datos:

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

Entonces, por ejemplo, cuando hago clic 5 veces, recibirá 5 llamadas y todas se ejecutarán en orden, necesito una forma de ejecutar la última llamada e ignorar las 4 llamadas anteriores, por lo que no tomará tiempo para ejecutar todos ellos.

PD: Pensé en deshabilitar el botón hasta que la función termine de ejecutarse, pero como estoy usando el botón para cargar al siguiente patient , esto no será conveniente porque estaríamos obligados a esperar a que carguen 4 pacientes para cargar el quinto paciente.

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

0

Debounce es una opción y la opción es pasar ref y obtener cancelToken cuando intente presionar nuevamente la misma API, cancelará la llamada anterior. Si existe y llama a la nueva solicitud de API, el siguiente ejemplo es la solución general o puede enviar cancelToken del componente y llámelo antes de la nueva llamada API

 // 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); } };

componente

 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!