Common Patterns: Nested Queries and Dependent Mutations
You'll learn how to orchestrate multiple tRPC operations where one depends on another's result, and how to keep your UI in sync when data changes.
Understanding Dependency Chains
In real applications, you often need to fetch data in stages: load a user, then load their posts, then load comments on a specific post. Similarly, after creating something, you might need to refresh related data. tRPC queries and mutations excel at this because types flow through each step automatically.
Think of it like a recipe where you can't start step 3 until step 2 finishes — but TypeScript ensures you're passing the right ingredients between steps.
Nested Queries: The Waterfall Pattern
You might call one query, extract its result, then use that result as input to another query. The types from the first query's output automatically satisfy the second query's input requirements:
// Client component
const userId = "user_123";
// First query
const userQuery = trpc.user.getById.useQuery({ id: userId });
// Second query depends on first
const postsQuery = trpc.posts.getByAuthor.useQuery(
{ authorId: userQuery.data?.id ?? "" },
{ enabled: !!userQuery.data?.id } // Only run when we have the ID
);
The enabled option prevents the second query from running prematurely. TypeScript knows userQuery.data?.id might be undefined, so you handle that before passing it along.
Dependent Mutations and Cache Invalidation
After a mutation completes, you typically need to refresh related queries. tRPC React Query integration gives you utils.invalidate() to mark data as stale:
const createPostMutation = trpc.posts.create.useMutation({
onSuccess: (newPost, variables, context) => {
// Invalidate and refetch the posts list
utils.posts.getByAuthor.invalidate({ authorId: newPost.authorId });
// Optionally invalidate related user data
utils.user.getById.invalidate({ id: newPost.authorId });
}
});
After creating a post, the posts query automatically refetches because you've marked its cache entry as invalid. TypeScript ensures you're passing the correct parameters to invalidate() — they must match the original query's input shape.
Optimistic Updates Pattern
For better UX, you can update the UI immediately before the server responds, then roll back if it fails:
const updatePostMutation = trpc.posts.update.useMutation({
onMutate: async (updatedPost) => {
// Cancel outgoing queries
await utils.posts.getById.cancel({ id: updatedPost.id });
// Snapshot current value
const previous = utils.posts.getById.getData({ id: updatedPost.id });
// Optimistically update
utils.posts.getById.setData({ id: updatedPost.id }, updatedPost);
return { previous };
},
onError: (err, updatedPost, context) => {
// Roll back on error
if (context?.previous) {
utils.posts.getById.setData({ id: updatedPost.id }, context.previous);
}
}
});
Every method here is fully typed — setData expects the exact shape your query returns.
Coordinating Multiple Mutations
Sometimes you need to run mutations in sequence, with each depending on the previous result:
const createUserMutation = trpc.user.create.useMutation();
const assignRoleMutation = trpc.roles.assign.useMutation();
async function handleSignup(userData, roleId) {
const newUser = await createUserMutation.mutateAsync(userData);
await assignRoleMutation.mutateAsync({
userId: newUser.id, // Type-safe: newUser.id is correctly typed
roleId
});
// Invalidate relevant queries
utils.user.list.invalidate();
}
Using mutateAsync lets you await the result and pass it type-safely to the next operation.
Key Takeaway: TypeScript's inference across tRPC queries and mutations lets you chain operations safely, while cache invalidation and optimistic updates keep your UI responsive and consistent — all without manually managing type definitions between operations.