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.
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>