-
-
Notifications
You must be signed in to change notification settings - Fork 3.7k
Open
Description
CodeSandbox: https://codesandbox.io/p/sandbox/loving-artem-skh7m5
import { useMemo } from "react";
import {
queryOptions,
experimental_streamedQuery as streamedQuery,
useQuery,
useQueryClient,
} from "@tanstack/react-query";
type Chunk = { event: "partial" | "final"; data: unknown[] };
type Result = {
previous?: Chunk;
current: Chunk;
final?: Chunk;
};
export function postQueryOptions(data?: unknown) {
const emptyResult: Result = {
current: { event: "partial", data: [] },
};
return queryOptions({
queryKey: ["post", data],
initialData: emptyResult,
placeholderData: emptyResult,
queryFn: () => {
throw new Error("Error");
},
// queryFn: streamedQuery({
// initialValue: emptyResult,
// streamFn: async function* ({ signal }) {
// // return new Error("Error");
// throw new Error("Error");
// //const stream = await api.post(data, {
// // fetch: { signal },
// //});
// //if (stream.error) throw stream.error;
// //for await (const chunk of stream.data) yield chunk;
// },
// reducer: (acc: Result, chunk: Chunk) => ({
// previous: acc.current,
// current: chunk,
// final: chunk.event === "final" ? chunk : undefined,
// }),
// }),
staleTime: Infinity,
});
}
export default function App() {
const queryClient = useQueryClient();
const options = useMemo(() => postQueryOptions(undefined), []);
const query = useQuery(options);
return (
<div>
<button
onClick={() => queryClient.refetchQueries(options)}
disabled={query.isFetching}
>
Post
</button>
<button
onClick={() => queryClient.cancelQueries(options)}
disabled={!query.isFetching}
>
Stop
</button>
{query.isError && <pre>Error: {query.error.message}</pre>}
{!query.isError && <pre>{JSON.stringify(query.data, null, 2)}</pre>}
</div>
);
}Originally posted in #9065 (comment)
Metadata
Metadata
Assignees
Labels
No labels