Search code examples
rtk-query

Calling invalidateTags with a specific ID seems to also clear the cache for other IDs


I have the following endpoint which provides tags using the id argument:

getNewsletter: builder.query<NewsletterGetResult, number>({
        query: id => `/newsletter/${id}`,
        providesTags: (result: any, error: any, arg: number) => [
            {type: 'Newsletter', id: arg}
        ]
    })

Elsewhere in the code, I'm calling invalidateTags with an argument which matches the above endpoint's tags:

dispatch(newsletterApi.util.invalidateTags(invalidatePayload as any[]));

Finally, the above endpoint is used in a component:

useGetNewsletterQuery(Number.parseInt(id as string));

The problem is that calling invalidateTags with a specific ID appears to clear the cache for all IDs

Please see the screenshare below for an example of how this manifests itself in my app

https://www.loom.com/share/123e5638c8b94ba5912e15dee152caad?sid=e205ed20-000b-4fd1-9aba-0054647adae5

In the screenshare, the left side contains a component with ID 82679 while the right side contains the same component with ID 82725. The console output on the left side shows the argument passed to invalidateTags when a change is made to the component:

{type: 'Newsletter', id: 82679}

After this happens, a progress bar appears in the component on the right side of the screen, which indicates that the cache was cleared and the query re-ran (the progress bar only appears when the query's isFetching property returns true), even though the ID does not match that of the argument passed to invalidateTags.

Please let me know whether this is an actual issue or there's a gap in my understanding of the invalidateTags behavior.


Solution

  • It looks like I misdiagnosed the issue. The arguments sent to invalidateTags included 'Newsletter' as well as {type: 'Newsletter', id: 82679}. I was previously under the impression that passing a tag type without an ID would only affect endpoints which don't use IDs and therefore assumed that the endpoint in question, which contains

    providesTags: (result: any, error: any, arg: number) => [
            {type: 'Newsletter', id: arg}
        ]
    

    would be unaffected. But it appears that the type alone trumps the IDs.