I am trying to cancel any previous / pending requests, if they are taking too long and the user navigates to another component, currently the query takes in a state value, and when it changes the component re-renders which is fine and the desired behaviour. However looking in the network tab the requests are still pending. Is there a way in react query to cancel any previous requests. I have attempted the query cancel based on the docs but its not correct as it's not cancelling.
const [value, setValue] = React.useState<boolean>(false);
const getData = async (value: number): Promise<any> => {
const CancelToken = axios.CancelToken
const source = CancelToken.source()
const response = await axios.get(`https://xxxxxx?value=${value}`, {
cancelToken: source.token,
}).then(res => res.data);
if (CancelToken) {
response.cancel = () => {
source.cancel('Query was cancelled by React Query')
}
}
return response;
}
const { data: result, status, error, isFetching }: any = useQuery(['getData', value], () => getData(value),
{
refetchOnWindowFocus: false,
}
);