Repository navigation
Open
Labels
next-major/definiteDefinite things for next major
Description
Describe the feature you'd like to request
Hi, I'm very grateful that trpc supports streaming!
I have read the HTTP Batch Stream Link documentation and implemented the query as it was written and was able to confirm that useQuery works fine.
However, when I implement mutation as well, the value of data in useMutation is AsyncGenerator.
// @filename: server.ts
import { publicProcedure, router } from './trpc';
const appRouter = router({
examples: {
iterable: publicProcedure.query(async function* () {
for (let i = 0; i < 3; i++) {
await new Promise((resolve) => setTimeout(resolve, 500));
yield i;
}
}),
iterable2: publicProcedure.mutation(async function* () {
for (let i = 0; i < 10; i++) {
await new Promise((resolve) => setTimeout(resolve, 500));
yield i;
}
}),
},
});
export type AppRouter = typeof appRouter;
// @filename: client.tsx
import { createTRPCClient, unstable_httpBatchStreamLink } from '@trpc/client';
import type { AppRouter } from './server';
const trpc = createTRPCClient<AppRouter>({
links: [
unstable_httpBatchStreamLink({
url: 'http://localhost:3000',
}),
],
});
// iterable.data is number[] | undefined
const iterable = trpc.examples.iterable.useQuery();
// iterable2.data is AsyncGenerator<number, void, unknown> | undefined
const iterable2 = trpc.examples.iterable2.useMutation();I would like useMutation to reflect the streaming response in the data as well as useQuery.
Describe the solution you'd like to see
I checked the #5741 to see if I could somehow determine the cause myself, but I could not figure out what the difference is between query and mutation.
I tried to change useMutation as well as useQuery but could not get it to work.
Please see comments on code.
const hook = __useMutation(
{
...opts,
mutationKey: mutationKey,
mutationFn: async (input) => {
const result = await client.mutation(
...getClientArgs([path, { input }], opts),
);
if (isAsyncIterable(result)) {
// is this correct?
const mutationCache = queryClient.getMutationCache();
const mutation = mutationCache.build(queryClient, {
mutationKey,
});
// error: setState is not exist
await mutation.setState({
data: [],
status: 'success',
});
const aggregate: unknown[] = [];
for await (const value of result) {
aggregate.push(value);
// error: setState is not exist
mutation.setState({
data: [...aggregate],
});
}
return aggregate;
}
return result;
},
onSuccess(...args) {
const originalFn = () =>
opts?.onSuccess?.(...args) ?? defaultOpts?.onSuccess?.(...args);
return mutationSuccessOverride({
originalFn,
queryClient,
meta: opts?.meta ?? defaultOpts?.meta ?? {},
});
},
},
queryClient,
) as UseTRPCMutationResult<unknown, TError, unknown, unknown>;Describe alternate solutions
As a workaround, it is still possible to handle AsyncGenerator on the client side as follows.
const [text, setText] = useState<string>('');
const iterable = trpc.examples.iterable.useMutation();
const callMutation = async () => {
iterable.mutate(
{ text: inputText },
{
onSuccess: async (data) => {
for await (const val of data) {
setText((prev) => prev + val);
}
},
},
);
};Additional information
👨👧👦 Contributing
- 🙋♂️ Yes, I'd be down to file a PR implementing this feature!
Metadata
Metadata
Assignees
Labels
next-major/definiteDefinite things for next major
Activity
KATT commentedon Jul 2, 2024
Started in #5850 - feel free to fork it and help me finish it, it needs some digging in tanstack query internals
KATT commentedon Nov 2, 2026
🤖 In v12, a mutation that returns an async iterable fills in as it streams:
useMutation(trpc.chat.send.streamedMutationOptions())runs it,useQuery(trpc.chat.send.chunksOptions())holds the chunks received so far, and when the stream ends the mutation'sdatais the array of chunks rather than anAsyncGenerator. The stream can also stop when the last reader unmounts, or on demand. https://v12.trpc.io/v12/docs/integrations/tanstack-query/streamed-mutations. v12 isn't released yet and there's no ETA.