tRPC v11 with TanStack Query on TanStack Start! Part 1

By Jack Herrington

Share:

Key Concepts

  • tRPC v11 integration with TanStack Query
  • create-ts-router-app for building TanStack Router applications
  • tRPC client and server setup
  • TanStack Start API route creation
  • React hook for tRPC connection (useTRPC)
  • Server-side rendering with tRPC
  • Using tRPC outside of React context

Setting Up tRPC with TanStack Start

  1. Project Initialization:
    • Use create-ts-router-app to scaffold a new TanStack Router application.
    • Select the "Add-ons" functionality for additional features.
    • Include options like TanStack Query, Start, Clerk (for future use), and Shadcn UI.
    • Optionally, integrate the TanStack Chat example for a full-featured AI assistant demo with guitar data.
  2. Installing Dependencies:
    • Install necessary libraries: trpc-client, trpc-server, @trpc/react-query, superjson, and zod.
  3. Creating the tRPC Directory:
    • Create a trpc directory inside the src folder to house tRPC-related files.
  4. Initializing tRPC:
    • Create an init.ts file to initialize the tRPC setup.
    • Use initTRPC to create the tRPC setup, providing T for type inference.
    • Obtain router from T to create the tRPC router.
    • Use publicProcedure to define public RPC procedures.
  5. Defining the Router:
    • Create a router.ts file to define the tRPC RPC functions.
    • Import createTRPCRouter and publicProcedure from the initialized tRPC setup.
    • Import the guitar data (e.g., guitaristData).
    • Create a guitarRouter using createTRPCRouter.
    • Define procedures within the guitarRouter:
      • list: Returns the list of all guitars.
      • byID: Takes an id as input (validated by Zod) and returns the guitar with the matching ID.
    • Create the main tRPC router by combining the guitarRouter.
    • Export the type of the tRPC router for type safety.
  6. Creating the TanStack Start API Route:
    • Create an API route file in src/routes/api/trpc/[...].ts (using the TanStack Start file-based routing convention).
    • Import the tRPC router.
    • Create an API file route with get and post handlers.
    • Pass the requests to a handler that wraps the fetchRequestHandler from @trpc/server/adapters/standalone.
  7. Testing the Endpoint:
    • Start the development server.
    • Make an API request to /api/trpc/guitars.list to verify the tRPC endpoint is working.

Integrating tRPC with React and TanStack Query

  1. Creating the React Hook:
    • Create a react.ts file in the trpc directory.
    • Import createTRPCContext from @trpc/react-query.
    • Import the tRPC router definition.
    • Use createTRPCContext to create the useTRPC hook and the TRPCProvider component.
  2. Connecting with TanStack Query:
    • Modify the TanStack Query setup in Integrations/tanstack-query/index.tsx.
    • Import the TRPCProvider component.
    • Create a tRPC client using createTRPCClient.
    • Use httpBatchLink as the transport layer.
    • Implement a getURL function to determine the correct URL (absolute for server-side, relative for client-side).
    • Upgrade the TanStack Query client to use superjson for serialization and deserialization.
    • Add the tRPC client to the context.
    • Replace the QueryClientProvider with the TRPCProvider.
  3. Wrapping the Application:
    • Modify the base router to wrap the application in the TRPCProvider.
    • Use the routerWithQueryClient function to handle the TanStack Query provider functionality.
  4. Ensuring Type Safety:
    • In the root route, add trpc to the router context to ensure full type safety.

Implementing tRPC Queries in React Components

  1. Fetching Data in a Component:
    • Import useQuery from TanStack Query and useTRPC from the trpc/react file.
    • Use useTRPC to get the tRPC client.
    • Use useQuery to make the tRPC call (e.g., trpc.guitars.list.useQuery()).
    • Map the data to the component's state.
  2. Server-Side Rendering:
    • Create a loader in the route to prefetch the query.
    • Use the loader to prefetch the data and save it as part of the page.
    • The component will then use the prefetched data, avoiding the initial "blinking" behavior.
    • The data will be included in the returned HTML, improving SEO.
  3. Parameterized Queries:
    • On the details page, get the ID from the route parameters using useParams.
    • Pass the ID to the byID procedure in the tRPC router.
    • Use useQuery to fetch the data with the ID parameter.

Using tRPC Outside of React Context

  1. Accessing the tRPC Client:
    • Import the tRPC client created in the root provider.
  2. Making Queries:
    • Use the tRPC client directly to make queries (e.g., await trpc.guitars.list.query()).
    • This allows you to use tRPC in non-React contexts, such as AI tools or server-side functions.

Example: Integrating tRPC with the AI Assistant

  1. Modifying the Tool Definition:
    • In the utils/demo-tools.ts file, modify the getGuitarsTool definition.
    • Import the tRPC client.
    • In the execute function, use the tRPC client to fetch the guitar list (e.g., await trpc.guitars.list.query()).
  2. Testing the Integration:
    • Go to the AI assistant in the guitar demo.
    • Ask for a guitar recommendation.
    • The AI assistant will use the tRPC client to fetch the guitar data and provide a recommendation.

Conclusion

The video demonstrates how to integrate tRPC v11 with TanStack Query in a TanStack Start application. It covers setting up the tRPC client and server, creating API routes, implementing queries in React components, enabling server-side rendering, and using tRPC outside of the React context. The example of integrating tRPC with an AI assistant showcases the flexibility and power of tRPC for building type-safe and efficient data fetching solutions. The next video will cover mutations.

Chat with this Video

AI-Powered

Load the transcript when you're ready to chat so the initial page stays lighter.

Ready to summarize another video?

Summarize YouTube Video