How do I fetch data conditionally?
Sorry if this is a stupid question.
I know that there is the
mutation
queries to do some actions and queries
for getting data.
I need to get data conditionally, I don't need to get a certain data but only on some specific event, I don't know if there's an option for that like the useMutation
and useQuery
.
I've tried fetch
, but it seems like I don't use the right client configuration?

10 Replies
I've changed the client to this:
and used it like so:
but I got these errors:
Seems like it sends
undefined
instead of the object I've included~I tried to mimic the
useQuery
by sending: input: {"0":{"json":{"text":"Hallo"}}}
but still fails with different err:
While I've received the data in the server just fine

I would recommend using tanstack-react-query or react-query here (could also be that this is also in @trpc/react, not sure), where you can pass an "enabled" option to only fetch when this is or becomes true.
It’s okay to use the vanilla client in the same app as the react query integration, you just won’t benefit from caching unless you manually update the cache
You can also use react query’s prefetching APIs
I thought I'd just fetch data from server without having to use React hooks and store the parameters in some state or ref. I might just skip tRPC for this one and do a simple Express GET request, although it makes things inconsistent.
This is also a valid option depending on use case
I need to fetch inside an event listener and act independently from the UI.
I just think the recommended way is more complex than necessary.
Prefetching or vanilla client then
But updating some state which drives a useQuery is more react-query-like
I'll try to make the vanilla client work, it gave me some error relating to media type, idk...