How should I set query data if the query key is different from useQuery hooks?
Hi folks, I encounter a challenge, so I would like to seek some helps. I'm building an omnichannel messaging app. The app is integrated with WhatsApp, Facebook Messenger, Telegram, etc. I'm implementing the following features:
1. There is a 'channel filter' option where the user can select a specific channel, or they can choose 'all' to view messages from all channels.
2. When receiving messages, I need to append them to the specific channel by using setQueryData or setQueriesData.
Due to the requirement of supporting 'all' in read operations while ensuring that write operations append messages to specific channels, there is a possibility of having different query keys between the read and write functionalities. Consequently, appending a message to a specific channel solely based on the channel parameters can be challenging.
An example code for better illustrate:
READ:
WRITE:
Is there any elegant solution for this use case? thank you!!!
2 Replies
rare-sapphire•3y ago
You can use
setQueriesData with a predicate to filter the keys you need to update: https://tanstack.com/query/latest/docs/react/guides/filters#query-filters
That way, you can update both the query for the specific channel, as well as the one with channel: undefined in one operationFilters | TanStack Query Docs
Some methods within TanStack Query accept a QueryFilters or MutationFilters object.
Query Filters
eager-peachOP•3y ago
@julien Thanks a lot!! My alternative solution is to treat 'all' as a virtual channel. When the user chooses 'all', it will append the received messages to the 'all' channel in the cache instead of appending them to a specific channel. Therefore, both reading and writing will rely on the same query key. But, I will try using a predicate function to see how it will work!