T
TanStack3y ago
eager-peach

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:
useInfiniteQuery([
'messages',
{
id: 'string',
channel: undefined (undefined will fetch all messages from all channels) |'whatsapp' | 'messager' | 'telegram'
}
])
useInfiniteQuery([
'messages',
{
id: 'string',
channel: undefined (undefined will fetch all messages from all channels) |'whatsapp' | 'messager' | 'telegram'
}
])
WRITE:
const onMessageReceive = (newMessage) => {
// Setting query data for a specific channel doesn't work if the query key is different from useInfiniteQuery
queryClient.setQueryData(
[
"messages",
{
id: "string",
channel: "whatsapp" | "messager" | "telegram",
},
],
(oldData) => {}
);
};
const onMessageReceive = (newMessage) => {
// Setting query data for a specific channel doesn't work if the query key is different from useInfiniteQuery
queryClient.setQueryData(
[
"messages",
{
id: "string",
channel: "whatsapp" | "messager" | "telegram",
},
],
(oldData) => {}
);
};
Is there any elegant solution for this use case? thank you!!!
2 Replies
rare-sapphire
rare-sapphire3y 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 operation
Filters | TanStack Query Docs
Some methods within TanStack Query accept a QueryFilters or MutationFilters object. Query Filters
eager-peach
eager-peachOP3y 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!

Did you find this page helpful?