How do I tell useQuery that initial data is prefetched on the server?
I have a Remix app and in my loader function I prefetch the data. Then on the client side I use useQuery as described in the docs Remix example. However the type of my data is
MyData | undefined
because useQuery doesn't know the initial data will be there. How do I solve that? For now I solved it by setting initialData: {} as MyData
in useQuery but I wonder if there is a better way?9 Replies
modern-teal•9mo ago
How does that loader data wind up in the query cache if not via initialData? loader runs on the server, right?
spiritual-aquaOP•9mo ago
Yes. Like this: https://tanstack.com/query/latest/docs/framework/react/guides/ssr#full-remix-example
Server Rendering & Hydration | TanStack Query React Docs
In this guide you'll learn how to use React Query with server rendering. See the guide on for some background. You might also want to check out the before that. For advanced server rendering patterns,...
spiritual-aquaOP•9mo ago
My loader code (server side):
my client usage of
useQuery
:
spiritual-aquaOP•9mo ago
loader data wind up in the query cache if not via initialDataUsing hydration APIs. This part is explaned here https://tanstack.com/query/latest/docs/framework/react/guides/ssr#using-the-hydration-apis
Server Rendering & Hydration | TanStack Query React Docs
In this guide you'll learn how to use React Query with server rendering. See the guide on for some background. You might also want to check out the before that. For advanced server rendering patterns,...
modern-teal•9mo ago
Okay, with hydration api, the best way to get type-safety is using suspense. Not sure if remix wraps routes in suspense boundaries but tanstack router does and that has worked great
spiritual-aquaOP•9mo ago
What do you mean? Are there some docs for this or examples?
modern-teal•9mo ago
You can
useSuspenseQuery
instead of useQuery
. The react docs explain what suspense isspiritual-aquaOP•9mo ago
I know what suspense is but didn't hear about
useSuspenseQuery
yet. Interesting, thx. However, according to the docs cancellation doesn't work which is not ideal.
Also not sure what does this part mean:
what happens when there is an error?modern-teal•9mo ago
It will throw to error boundaries