T
TanStack3y ago
exotic-emerald

Invalidate query in react native

Using an infinite query in react native. One screen has
useInfiniteQuery({
queryKey: ['posts', user.uid]
...
useInfiniteQuery({
queryKey: ['posts', user.uid]
...
On another screen I allow the user to update their profile picture. After the image is uploaded I run
queryClient.invalidateQueries({ queryKey: [user.uid] })
queryClient.invalidateQueries({ queryKey: [user.uid] })
To invalidate all queries related to that user (i.e. posts, comments, etc that would all have the profile picture associated with them) . This however is not causing my list of posts to update when I return to the screen. Only after I refresh (which triggers a re-fetch manually) will it update the posts. Why might this be?
5 Replies
exotic-emerald
exotic-emeraldOP3y ago
@M00LTi would it matter if it was within a mutate or not?
wise-white
wise-white3y ago
Yes. You might want to share some code.
flat-fuchsia
flat-fuchsia3y ago
To invalidate all queries related to that user
that's not how it works. Query Keys hav a hierarchy - arrays have an order. if you want that, you'd need to put the id first in the key:
[user.uid, 'posts']
[user.uid, 'comments']
[user.uid, 'posts']
[user.uid, 'comments']
alternatively, an object structure also works well:
[{ user: user.uid, type: 'posts' }]
[{ user: user.uid, type: 'comments' }]
[{ user: user.uid, type: 'posts' }]
[{ user: user.uid, type: 'comments' }]
because with that, you can cross-invalidate: - everything post related with [{ type: 'posts'}] - everything for a single user with [{ user: user.uid }] I have a blogpost on this: https://tkdodo.eu/blog/leveraging-the-query-function-context#object-query-keys
Leveraging the Query Function Context
Use what React Query provides for optimal type safety
flat-fuchsia
flat-fuchsia3y ago
Only after I refresh
invalidate refetches active queries and marks inactive ones as stale so that they will be refetched once they are used again. You can use refetchQueries instead to trigger a refetch immediately.

Did you find this page helpful?