TanStackT
TanStack3y ago
31 replies
rubber-blue

TRPC + React Query

I am using Tanstack router and query with TRPC. I am transitioning an application to use the new router. I am normally doing data fetching at the component with hooks using react query like so:
const posts = trpc.posts.getPosts.useQuery();

You cannot use these hooks inside of the loader method for routes, so I am using the trpc proxy client to create a none react client to use, so I can use:
loader: () => trpcVanillaClient.posts.getPosts.query()

I am using both clients right now. I am using the vanillaClient to handle fetching data inside the route loader, while I am using the reactTrpc client to handle mutations so I can have access to the hooks inside the component.

Here is an example of a route that is using both clients. trpcVanillaClient and trpcRect. I am invalidating the route's loader data after the mutation is successful
// The route using the vanilla trpc client
export const Route = new FileRoute("/").createRoute({
  component: Home,
  loader: () => trpcVanillaClient.posts.getPosts.query()
});

...
// The mutation in the component (using the reactTrpc client):
const createPostMutation = trpcReact.posts.createPost.useMutation({
    onSuccess: () => {
      router.invalidate();
    }
  });


Is there a proper way to handle this? Are there any downsides to having both trpc clients? Thanks
image.png
Was this page helpful?