1

I'm attempting to cancel a query in react tansktack query. I have a hook that detects if the user is offline or online. When the user is offline I want to immediatlly cancel the query to show some offline downloaded data. I have attempted to do so but the query does not cancel, it only fails.
My logic:

export default function Body({ searchText, id, alvoId }: BodyProps) {
  const { isOnline } = useOnlineStatus();
  const cancelToken = useRef<CancelTokenSource>();

  const { data, isError, isLoading, refetch  } = useQuery({
    queryKey: [`dsc/${id}`],
    queryFn: async () => {
      cancelToken.current = axios.CancelToken.source();
      const token = cancelToken.current?.token;

      const promise = await actionsGet(id, token);

      return promise;
    },
  });

  if (isError && isOnline) {
    showToast('customToast', 'Error', 'Verifique a conexão com a internet', 'error');
  }

useEffect(() => {
    if (isOnline) {
      setDisciplina(data?.content || []);
      handleDownloadedIds();
    } else {
      cancelToken.current?.cancel();
      if (!data) {
        handleDownloadedDisciplina();
      } else {
        setDisciplina(data?.content || []);
        handleDownloadedIds();
      }
    }
  }, [data, isOnline]);

My versions:

"@tanstack/react-query": "^4.24.4",

The query it is calling:

export async function actionsGet(
  id: string,
  cancelToken?: any
): Promise<any> {
  const response = await api.get(`/data/${id}`, {
    headers: {
      modulo: 'STUFF',
    },
    cancelToken: cancelToken,
  });

  return response.data;
}
Nilton Schumacher F
  • 814
  • 3
  • 13
  • 43

1 Answers1

2

Per the docs you can manually cancel a query using its queryKey:

const queryClient = useQueryClient();

queryClient.cancelQueries({ queryKey: ['todos'] })
Kipnoedels
  • 1,118
  • 7
  • 22