Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/query-options-pass-through.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@tanstack/query-db-collection': minor
---

Add top-level Query Collection support for additional Query observer options while preserving QueryClient defaultOptions behavior.
44 changes: 31 additions & 13 deletions docs/collections/query-collection.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,9 @@ The `queryCollectionOptions` function accepts the following options:

### Query Options

Query Collections use TanStack Query internally, but `queryCollectionOptions` is not a full `QueryObserverOptions` pass-through. It exposes only the Query options supported by the collection adapter. Fields that affect row materialization, collection identity, and synchronization are handled by the adapter itself.
Query Collections use TanStack Query internally and expose supported Query observer options as top-level `queryCollectionOptions` fields.

The following Query options are forwarded to the underlying Query observer:
The following top-level Query Collection options are forwarded to the underlying Query observer:

- `select`: Function that extracts the row array TanStack DB materializes from a wrapped Query response
- `enabled`: Whether the query should automatically run (default: `true`)
Expand All @@ -67,9 +67,28 @@ The following Query options are forwarded to the underlying Query observer:
- `retryDelay`: Delay between retries
- `staleTime`: How long data is considered fresh
- `gcTime`: How long unused query data stays in the Query cache
- `refetchOnWindowFocus`: Whether to refetch when the window regains focus
- `refetchOnReconnect`: Whether to refetch when the network reconnects
- `refetchOnMount`: Whether to refetch when the observer mounts
- `networkMode`: Query network mode
- `meta`: Metadata passed to the query function context. Query Collections may add `loadSubsetOptions` for on-demand queries.

Except for `meta`, these options are only passed to TanStack Query when you define them. If you omit them, `QueryClient.defaultOptions` can still apply.
```ts
const todosCollection = createCollection(
queryCollectionOptions({
queryKey: ["todos"],
queryFn: fetchTodos,
queryClient,
getKey: (todo) => todo.id,
refetchOnWindowFocus: true,
refetchOnReconnect: true,
refetchOnMount: "always",
networkMode: "online",
})
)
```

Top-level `meta` is always merged by Query Collection so it can add on-demand `loadSubsetOptions`. Other supported top-level Query options are only passed to TanStack Query when you define them. If you omit them, `QueryClient.defaultOptions` can still apply.

Some fields are owned or reinterpreted by the collection adapter rather than treated as ordinary Query option pass-through:

Expand All @@ -81,20 +100,19 @@ Some fields are owned or reinterpreted by the collection adapter rather than tre
- `getKey`: Extracts each row's stable TanStack DB key.
- Mutation handlers such as `onInsert`, `onUpdate`, and `onDelete`.

Other TanStack Query options are not currently exposed through `queryCollectionOptions`. Common examples include:
Some TanStack Query fields are owned or reinterpreted by Query Collection and are intentionally not exposed as ordinary Query observer options:

- `queryKey`, `queryFn`, and `queryClient`
- `select` (Query Collection uses this for row extraction, not TanStack Query's observer-level `select` contract)
- `meta` (merged by Query Collection so on-demand `loadSubsetOptions` can be included)
- `subscribed` (Query Collection owns the observer subscription lifecycle)
- `structuralSharing` and `notifyOnChangeProps` (managed by Query Collection synchronization)

- `initialData`
- `placeholderData`
- `refetchOnWindowFocus`
- `refetchOnReconnect`
- `refetchOnMount`
- `networkMode`
- `throwOnError`
- configurable `structuralSharing`
Other semantic options, such as `initialData`, `placeholderData`, and TanStack Query observer-level `select`, are intentionally deferred until their Query Collection behavior is explicitly designed.

### Using with `queryOptions(...)`

If your app already uses TanStack Query's `queryOptions` helper (e.g. from `@tanstack/react-query`), you can spread those options into `queryCollectionOptions`. Note that `queryFn` must be explicitly provided since query collections require it both in types and at runtime:
If your app already uses TanStack Query's `queryOptions` helper (e.g. from `@tanstack/react-query`), you can spread compatible top-level options into `queryCollectionOptions`. Note that `queryFn` must be explicitly provided since query collections require it both in types and at runtime, and Query Collection's `select` option is for row extraction rather than TanStack Query observer-level selection:

```typescript
import { QueryClient } from "@tanstack/query-core"
Expand Down
126 changes: 116 additions & 10 deletions packages/query-db-collection/src/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,40 @@ type InferSchemaInput<T> = T extends StandardSchemaV1

type TQueryKeyBuilder<TQueryKey> = (opts: LoadSubsetOptions) => TQueryKey

const queryObserverOptionKeys = [
`enabled`,
`refetchInterval`,
`retry`,
`retryDelay`,
`staleTime`,
`gcTime`,
`refetchOnWindowFocus`,
`refetchOnReconnect`,
`refetchOnMount`,
`networkMode`,
] as const

type QueryObserverOptionKey = (typeof queryObserverOptionKeys)[number]

type QueryObserverOptionValues = Pick<
QueryObserverOptions<Array<any>, any, Array<any>, Array<any>, any>,
QueryObserverOptionKey
>

function pickDefinedQueryObserverOptions(
config: Partial<QueryObserverOptionValues>,
): Partial<QueryObserverOptionValues> {
const options: Partial<QueryObserverOptionValues> = {}

for (const key of queryObserverOptionKeys) {
if (config[key] !== undefined) {
;(options as Record<QueryObserverOptionKey, unknown>)[key] = config[key]
}
}

return options
}

/**
* Configuration options for creating a Query Collection
* @template T - The explicit type of items stored in the collection
Expand Down Expand Up @@ -129,6 +163,34 @@ export interface QueryCollectionConfig<
TQueryData,
TQueryKey
>[`gcTime`]
refetchOnWindowFocus?: QueryObserverOptions<
TQueryData,
TError,
Array<T>,
TQueryData,
TQueryKey
>[`refetchOnWindowFocus`]
refetchOnReconnect?: QueryObserverOptions<
TQueryData,
TError,
Array<T>,
TQueryData,
TQueryKey
>[`refetchOnReconnect`]
refetchOnMount?: QueryObserverOptions<
TQueryData,
TError,
Array<T>,
TQueryData,
TQueryKey
>[`refetchOnMount`]
networkMode?: QueryObserverOptions<
TQueryData,
TError,
Array<T>,
TQueryData,
TQueryKey
>[`networkMode`]
persistedGcTime?: number

/**
Expand Down Expand Up @@ -596,6 +658,10 @@ export function queryCollectionOptions(
retryDelay,
staleTime,
gcTime,
refetchOnWindowFocus,
refetchOnReconnect,
refetchOnMount,
networkMode,
persistedGcTime,
getKey,
onInsert,
Expand Down Expand Up @@ -1172,19 +1238,23 @@ export function queryCollectionOptions(
Array<any>,
any
> = {
...pickDefinedQueryObserverOptions({
enabled,
refetchInterval,
retry,
retryDelay,
staleTime,
gcTime,
refetchOnWindowFocus,
refetchOnReconnect,
refetchOnMount,
networkMode,
}),
queryKey: key,
queryFn: queryFunction,
meta: extendedMeta,
structuralSharing: true,
notifyOnChangeProps: `all`,

// Only include options that are explicitly defined to allow QueryClient defaultOptions to be used
...(enabled !== undefined && { enabled }),
...(refetchInterval !== undefined && { refetchInterval }),
...(retry !== undefined && { retry }),
...(retryDelay !== undefined && { retryDelay }),
...(staleTime !== undefined && { staleTime }),
...(gcTime !== undefined && { gcTime }),
}

const localObserver = new QueryObserver<
Expand Down Expand Up @@ -1876,6 +1946,23 @@ export function queryCollectionOptions(
// Enhanced internalSync that captures write functions for manual use
const enhancedInternalSync: SyncConfig<any>[`sync`] = (params) => {
const { begin, write, commit, collection } = params
let queryClientMounted = false

const mountQueryClient = () => {
if (!queryClientMounted) {
queryClient.mount()
queryClientMounted = true
}
}

const unmountQueryClient = () => {
if (queryClientMounted) {
queryClient.unmount()
queryClientMounted = false
}
}

mountQueryClient()

// Get the base query key for the context (handle both static and function-based keys)
const contextQueryKey =
Expand All @@ -1895,8 +1982,27 @@ export function queryCollectionOptions(
updateCacheData,
}

// Call the original internalSync logic
return internalSync(params)
// Call the original internalSync logic, pairing QueryClient mount with the
// collection sync lifecycle so focus/reconnect managers dispatch events for
// standalone QueryClient usage.
const syncResult = internalSync(params)
const sync =
typeof syncResult === `function`
? { cleanup: syncResult }
: typeof syncResult === `object`
? syncResult
: {}

return {
...sync,
cleanup: () => {
try {
sync.cleanup?.()
} finally {
unmountQueryClient()
}
},
}
}

// Create write utils using the manual-sync module
Expand Down
24 changes: 24 additions & 0 deletions packages/query-db-collection/tests/query.test-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,30 @@ describe(`Query collection type resolution tests`, () => {
// Create a mock QueryClient for tests
const queryClient = new QueryClient()

it(`should type supported top-level Query observer options and reject adapter-owned fields`, () => {
queryCollectionOptions<ExplicitType>({
id: `query-options-types`,
queryClient,
queryKey: [`query-options-types`],
queryFn: () => Promise.resolve([]),
getKey: (item) => item.id,
refetchOnWindowFocus: true,
refetchOnReconnect: true,
refetchOnMount: `always`,
networkMode: `online`,
})

queryCollectionOptions<ExplicitType>({
id: `query-options-subscribed-owned`,
queryClient,
queryKey: [`query-options-subscribed-owned`],
queryFn: () => Promise.resolve([]),
getKey: (item) => item.id,
// @ts-expect-error Query Collection owns observer subscription lifecycle.
subscribed: false,
})
})

it(`should prioritize explicit type in QueryCollectionConfig`, () => {
const options = queryCollectionOptions<ExplicitType>({
id: `test`,
Expand Down
Loading
Loading