Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

streamedQuery.md

45 lines2.3 KB

1---
2id: streamedQuery
3title: streamedQuery
4---
5​
6`streamedQuery` is a helper function to create a query function that streams data from an [AsyncIterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncIterator). Data will be an Array of all the chunks received. The query will be in a `pending` state until the first chunk of data is received, but will go to `success` after that. The query will stay in fetchStatus `fetching` until the stream ends.
7​
8To see `streamedQuery` in action, take a look at our chat example in the [examples/react/chat directory on GitHub](https://github.com/TanStack/query/tree/main/examples/react/chat).
9​
10```tsx
11import { experimental_streamedQuery as streamedQuery } from '@tanstack/react-query'
12​
13const query = queryOptions({
14 queryKey: ['data'],
15 queryFn: streamedQuery({
16 streamFn: fetchDataInChunks,
17 }),
18})
19```
20​
21> Note: `streamedQuery` is currently marked as `experimental` because we want to gather feedback from the community. If you've tried out the API and have feedback for us, please provide it in this [GitHub discussion](https://github.com/TanStack/query/discussions/9065).
22​
23**Options**
24​
25- `streamFn: (context: QueryFunctionContext) => Promise<AsyncIterable<TData>>`
26 - **Required**
27 - The function that returns a Promise of an AsyncIterable with data to stream in.
28 - Receives a [QueryFunctionContext](../../framework/react/guides/query-functions.md#queryfunctioncontext)
29- `refetchMode?: 'append' | 'reset' | 'replace'`
30 - Optional
31 - Defines how refetches are handled.
32 - Defaults to `'reset'`
33 - When set to `'reset'`, the query will erase all data and go back into `pending` state.
34 - When set to `'append'`, data will be appended to existing data.
35 - When set to `'replace'`, all data will be written to the cache once the stream ends.
36- `reducer?: (accumulator: TData, chunk: TQueryFnData) => TData`
37 - Optional
38 - Reduces streamed chunks (`TQueryFnData`) into the final data shape (`TData`).
39 - Default: appends each chunk to the end of the accumulator when `TData` is an array.
40 - If `TData` is not an array, you must provide a custom `reducer`.
41- `initialValue?: TData = TQueryFnData`
42 - Optional
43 - Defines the initial data to be used while the first chunk is being fetched.
44 - It is mandatory when custom `reducer` is provided.
45 - Defaults to an empty array.