MCPcopy Create free account
hub / github.com/TanStack/query / streamedQuery

Function streamedQuery

packages/query-core/src/streamedQuery.ts:51–120  ·  view source on GitHub ↗
({
  streamFn,
  refetchMode = 'reset',
  reducer = (items, chunk) =>
    addToEnd(items as Array<TQueryFnData>, chunk) as TData,
  initialValue = [] as TData,
}: StreamedQueryParams<TQueryFnData, TData, TQueryKey>)

Source from the content-addressed store, hash-verified

49 * @param initialValue - Initial value to be used while the first chunk is being fetched, and returned if the stream yields no values.
50 */
51export function streamedQuery<
52 TQueryFnData = unknown,
53 TData = Array<TQueryFnData>,
54 TQueryKey extends QueryKey = QueryKey,
55>({
56 streamFn,
57 refetchMode = 'reset',
58 reducer = (items, chunk) =>
59 addToEnd(items as Array<TQueryFnData>, chunk) as TData,
60 initialValue = [] as TData,
61}: StreamedQueryParams<TQueryFnData, TData, TQueryKey>): QueryFunction<
62 TData,
63 TQueryKey
64> {
65 return async (context) => {
66 const query = context.client
67 .getQueryCache()
68 .find({ queryKey: context.queryKey, exact: true })
69 const isRefetch = !!query && query.isFetched()
70 if (isRefetch && refetchMode === 'reset') {
71 query.setState({
72 ...query.resetState,
73 fetchStatus: 'fetching',
74 })
75 }
76
77 let result = initialValue
78
79 let cancelled: boolean = false as boolean
80 const streamFnContext = addConsumeAwareSignal<
81 OmitKeyof<typeof context, 'signal'>
82 >(
83 {
84 client: context.client,
85 meta: context.meta,
86 queryKey: context.queryKey,
87 pageParam: context.pageParam,
88 direction: context.direction,
89 },
90 () => context.signal,
91 () => (cancelled = true),
92 )
93
94 const stream = await streamFn(streamFnContext)
95
96 const isReplaceRefetch = isRefetch && refetchMode === 'replace'
97
98 for await (const chunk of stream) {
99 if (cancelled) {
100 break
101 }
102
103 if (isReplaceRefetch) {
104 // don't append to the cache directly when replace-refetching
105 result = reducer(result, chunk)
106 } else {
107 context.client.setQueryData<TData>(context.queryKey, (prev) =>
108 reducer(prev === undefined ? initialValue : prev, chunk),

Callers 2

chatQueryOptionsFunction · 0.85

Calls 8

addToEndFunction · 0.90
addConsumeAwareSignalFunction · 0.90
getQueryCacheMethod · 0.80
isFetchedMethod · 0.80
setStateMethod · 0.80
findMethod · 0.45
setQueryDataMethod · 0.45
getQueryDataMethod · 0.45

Tested by

no test coverage detected