I'm using Ky to make requests. I want to cancel the request in case the component unmounts. I have this code, where I'm using useEffect hook to send a signal to a function and cancel the request:
import React, { useEffect, useState } from 'react'
import ky, { HTTPError } from 'ky'
const MyComponent = (props) => {
/**
* Every time the StatisticalValidation instance changes retrieves its data from the backend
*/
useEffect(() => {
const abortController = new AbortController()
if (props.selectedStatisticalValidation.id) {
getStatValidationClinicalAttrs(abortController.signal)
}
/** On unmount aborts Ky's request */
return () => {
abortController.abort()
}
}, [props.selectedStatisticalValidation.id])
/** Make a request. */
const getStatValidationClinicalAttrs = (signal: AbortSignal) => {
const searchParams = { /* ... */ }
ky.get(url, { searchParams, timeout: 60000, signal }).then((response) => {
response.json().then(() => {
// ....
}).catch((err) => {
// ...
})
}).catch((err: HTTPError) => {
// ...
})
}
}
But It's not working, the request keeps in progress even when the unmounting function is correctly executed and the signal's aborted prop is true.
Some important considerations:
- I tried with
useRefbut that didn't work either. - If I create the
AbortControllerinside thegetStatValidationClinicalAttrs()and abort it in that function it works, as expected.