build<TQueryData> method
- QueryClient client,
- DefaultedQueryOptions<
TQueryData> options, { - QueryState<
TQueryData> ? state,
The query for options's key, creating it if it does not exist yet.
state is how a persistence layer restores a saved entry; it is used
only when the query is created here, and ignored when the key already
has one. A success state must carry data (hasData), or the first
result built from it would fail on a cast; one without is refused with
an ArgumentError in every build mode, as Query.setState refuses it,
so the mistake surfaces here and not later in an observer.
A restored QueryState.fetchStatus is normalised to
FetchStatus.idle. A snapshot taken mid-fetch says fetching or
paused, but no fetch survives the process it ran in: installed
verbatim it would make a query nothing is doing count towards
QueryClient.isFetching(), keep it out of garbage collection for
good, and leave a paused one that no reconnect could resume. TanStack
Query's hydration applies the same rule. Query.setState does not
normalise: it is the other half of a restore, the merge into a query
that already exists, and there a fetch may really be running.
Implementation
Query<TQueryData> build<TQueryData>(
QueryClient client,
DefaultedQueryOptions<TQueryData> options, {
QueryState<TQueryData>? state,
}) {
state?.validate();
final existing = get<TQueryData>(options.queryKey);
if (existing != null) {
return existing;
}
final query = Query<TQueryData>(
client: client,
cache: this,
queryKey: options.queryKey,
options: options,
state: state?.fetchStatus == FetchStatus.idle
? state
: state?.copyWith(fetchStatus: FetchStatus.idle),
);
// InitialData.compute may synchronously populate this key. That entry,
// rather than the losing constructor, is the cache's canonical query.
final canonical = get<TQueryData>(options.queryKey);
if (canonical != null) {
query.markRemoved();
return canonical;
}
add(query);
return query;
}