How to share data between different query keys?
For context I am working on a UI for a music player. I have an endpoint that returns information about the requested album, optionally you can request that the end point also include all the songs in the album.
Most places in the UI I don't need the songs to be fetched as they are only visible when the user navigates into the album.
I have a query like so
My problem is that since
includeSongs is a part of the queryKey, an album with the songs included or without get treated as a separate entry in the cache. Even though they are nearly the same, save for one field. Any suggestions to make this more efficient?5 Replies
absent-sapphireOP•3y ago
For some more context, this becomes an issue because I have a part of the app that handles user ratings for albums/artists/songs etc.
Whenever a user makes a rating I can update the cache with the new rating. This becomes a problem because I have to update the cache for both
['album', albumID', true] and ['album', albumID', false]harsh-harlequin•3y ago
Perhaps you could tread the album itself and songs as different entities that you fetch in entirely different queries?
absent-sapphireOP•3y ago
The album doesnt return doesnt include what songs belong to it if
includeSongs is false.foreign-sapphire•3y ago
For the issue with updating the cache, you don't have to manually update each entry. If you use
setQueriesData you can just pass ['album', albumID] and it should update both queries (it matches all queries whose key starts with ['album', albumID] - see Query filters: https://tanstack.com/query/v4/docs/react/guides/filters#query-filters).
https://tanstack.com/query/v4/docs/react/reference/QueryClient#queryclientsetqueriesdataFilters | TanStack Query Docs
Some methods within TanStack Query accept a QueryFilters or MutationFilters object.
Query Filters
QueryClient | TanStack Query Docs
QueryClient
The QueryClient can be used to interact with a cache:
absent-sapphireOP•3y ago
Thanks for that, I stumbled upon it and realized that is pretty much what I need.