skip to Main Content

I want to cancel pending calls on unmount of a component. I’m using react query 3.39.2. There are n api calls, and the query key is dynamic. I’ve shared the current code below, and it does not work. What am I doing wrong?

PS: It does go inside the if block.

const queryClinet = useQueryClient();
useEffect(() => {
return () => {
  queryClient.getQueryCache()
  .getAll()
  .forEach(query => {
    if(query.queryKey.includes('partOfMyKey'))
      queryClient.cancelQueries(query.queryKey);
      // queryClient.cancelQueries({ queryKey: query.queryKey });
  })
}
}, [window.location.href])

2

Answers


  1. You are almost there and missing a curly braces {} in your if statement.The code should be this :

    const queryClient = useQueryClient();
    
    useEffect(() => {
      return () => {
        queryClient.getQueryCache().getAll().forEach(query => {
          if (query.queryKey.includes('partOfMyKey')) {
            queryClient.cancelQueries(query.queryKey);
          }
        });
      };
    }, [window.location.href]);
    
    Login or Signup to reply.
  2. Query Cancellation alone doesn’t do much per default: It cancels the Query itself (so data is not stored), but it doesn’t abort the request.

    To achieve that, you need to forward the AbortSignal provided by react-query to your fetch function. How you do this depends on what you use for data fetching – the docs have multiple examples, but here is the one for fetch:

    const query = useQuery({
      queryKey: ['todos'],
      queryFn: async ({ signal }) => {
        const todosResponse = await fetch('/todos', { signal })
        return todoResponse.json()
      }
    })
    

    If the signal is passed to fetch, the Query will be cancelled automatically when the fetch is aborted. This will happen as soon as no component is mounted that is actively using the Query.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search