TanStackT
TanStack3y ago
2 replies
sacred-rose

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' 
  }
])



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) => {}
  );
};


Is there any elegant solution for this use case? thank you!!!
Was this page helpful?