T
TanStack2d ago
ratty-blush

Query without a queryFn but just manually using setQueryData?

I have a weird use case which probably means I'm doing something wrong, haha. I have a case where I'm streaming some events back from a server using Server Sent Events. There's some events I'd like to store in memory and make use of their results later. Since I already use TanStack Query, I thought I'd just leverage that. But basically I just want to manually manage the query data myself. I have this:
queryClient.setQueryDefaults(
[CHAT_SESSION_QUERY_KEY, chatSessionExternalKey, "metadata"],
{
gcTime: Infinity,
},
);
queryClient.setQueryData<ChatMetadata>(
[CHAT_SESSION_QUERY_KEY, chatSessionExternalKey, "metadata"],
(old) => (old ? { ...old, ...metadataUpdateRequest } : eventData),
);
queryClient.setQueryDefaults(
[CHAT_SESSION_QUERY_KEY, chatSessionExternalKey, "metadata"],
{
gcTime: Infinity,
},
);
queryClient.setQueryData<ChatMetadata>(
[CHAT_SESSION_QUERY_KEY, chatSessionExternalKey, "metadata"],
(old) => (old ? { ...old, ...metadataUpdateRequest } : eventData),
);
That works, but I run into trouble later when trying to use that query. Since useQuery needs a queryFn, I don't really know what to supply for that? I don't actually want to use a queryFn, I just want the useQuery to look up whatever data I've already manually stored (and keep it synced if I ever change it). Any ideas?
3 Replies
ratty-blush
ratty-blushOP2d ago
I should probably just use a vanilla context or something, huh?
conscious-sapphire
conscious-sapphire2d ago
Using WebSockets with React Query
A step-by-step guide on how to make real-time notifications work with react-query
conscious-sapphire
conscious-sapphire2d ago
Ideally you'd have a get endpoin that returns the data you want, and you can invalidate the query with each event. Or have it get once initially with staleTime Infinity and just update with setQueryData But also you can just use useQuery with just the queryKey, its not usually recommended because you will lose typesafety pretty easily.

Did you find this page helpful?