MCPcopy Index your code
hub / github.com/TanStack/db / queryOnce

Function queryOnce

packages/db/src/query/query-once.ts:90–134  ·  view source on GitHub ↗
(
  configOrQuery:
    | QueryOnceConfig<TContext>
    | ((
        q: InitialQueryBuilder,
      ) => QueryBuilder<TContext> & RootObjectResultConstraint<TContext>),
)

Source from the content-addressed store, hash-verified

88
89// Implementation
90export async function queryOnce<TContext extends Context>(
91 configOrQuery:
92 | QueryOnceConfig<TContext>
93 | ((
94 q: InitialQueryBuilder,
95 ) => QueryBuilder<TContext> & RootObjectResultConstraint<TContext>),
96): Promise<InferResultType<TContext>> {
97 // Normalize input
98 const config: QueryOnceConfig<TContext> =
99 typeof configOrQuery === `function`
100 ? { query: configOrQuery }
101 : configOrQuery
102
103 const query = (q: InitialQueryBuilder) => {
104 const queryConfig = config.query
105 return typeof queryConfig === `function` ? queryConfig(q) : queryConfig
106 }
107
108 // Create collection with minimal GC time; preload handles sync start
109 const collection = createLiveQueryCollection({
110 query,
111 gcTime: 1, // Cleanup in next tick when no subscribers (0 disables GC)
112 })
113
114 try {
115 // Wait for initial data load
116 await collection.preload()
117
118 // Check if this is a single-result query (findOne was called)
119 const isSingleResult =
120 (collection.config as { singleResult?: boolean }).singleResult === true
121
122 // Extract and return results
123 if (isSingleResult) {
124 const first = collection.values().next().value as
125 | InferResultType<TContext>
126 | undefined
127 return first as InferResultType<TContext>
128 }
129 return collection.toArray as unknown as InferResultType<TContext>
130 } finally {
131 // Always cleanup, even on error
132 await collection.cleanup()
133 }
134}

Callers 3

includes.test-d.tsFile · 0.85
select.test.tsFile · 0.85
query-once.test.tsFile · 0.85

Calls 4

preloadMethod · 0.45
valuesMethod · 0.45
cleanupMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…