ObservableQuery
API reference
An ObservableQuery is created by calling the client.watchQuery method.
It represents a query that can be observed for changes, allowing you to reactively update your UI.
Key Behaviors
RxJS Integration
ObservableQuery implements the RxJS InteropObservable interface which means you can convert it into an RxJS Observable via from(observableQuery).
It also provides the subscribe and pipe functions like an RxJS Observable.
Refer to the RxJS documentation for additional context and API options.
To get a single result from an ObservableQuery as a Promise, use the firstValueFrom helper:
1import { firstValueFrom, from } from "rxjs";
2
3// The `from` is necessary to turn `observableQuery` into an RxJS observable
4const result = await firstValueFrom(from(observableQuery));Subscription Lifecycle
ObservableQueryinstances are only registered withApolloClientwhile they have active subscribersUnsubscribing from an
ObservableQuerywhile a request is in flight does not terminate the requestUnsubscribing before any value has been emitted removes the query from the tracked list and makes it ineligible for query deduplication
Error Handling
ObservableQuerydoes not terminate on errors - instead it emits anextvalue with anerrorproperty. This ensuresObservableQuerysubscriptions can continue receiving updates after errors without resubscription.
Loading States
When
notifyOnNetworkStatusChangeistrue(the default), an initial loading state is emitted when subscribingObservableQuerypreservesdatawhen emitting a loading state unlessqueryorvariableschanged (note:@exportvariables are not considered for this check)When the query can be fulfilled by the cache or when the link chain responds synchronously, a loading state is omitted
cache-onlyqueries initialize withnetworkStatus: NetworkStatus.readywhen there is no data in the cachestandbyqueries initialize withnetworkStatus: NetworkStatus.readybefore subscribing to the query
Promise-returning Methods and retention
refetch()andreobserve()return aResultPromisewith an additional.retain()methodBy default, the network operation is cancelled when
ObservableQueryno longer requires the result, such as whenObservableQueryis unsubscribed or variables change, and the returnedPromisewill reject with anAbortErrorCalling
.retain()keeps the network operation running even when theObservableQueryno longer requires the resultsetVariables()andrefetch()guarantee that a value will be emitted from the observable, even when the result is deeply equal to the previous result
Active vs Inactive Queries
Active queries: Have at least one subscriber and are not skipped or have a
fetchPolicyofstandbyInactive queries: Have a subscriber but are either skipped or have a
fetchPolicyofstandbyObservableQuerys without subscribers but with an active network request are handled as if they had a subscriber for the duration of the queryOnly queries with subscribers can be refetched using
ApolloClient.refetchQueries
ObservableQuery functions
Used to stitch together functional operators into a chain.
Example
1 import { filter, map } from 'rxjs';
2
3 observableQuery
4 .pipe(
5 filter(...),
6 map(...),
7 )
8 .subscribe(x => console.log(x));Signature
1pipe(
2 operators: OperatorFunctionChain<ObservableQuery.Result<TData>, OperatorResult>
3): Observable<OperatorResult>Subscribes to the ObservableQuery.
Signature
1subscribe(
2 observerOrNext: Partial<Observer<ObservableQuery.Result<MaybeMasked<TData>>>> | ((value: ObservableQuery.Result<MaybeMasked<TData>>) => void)
3): SubscriptionParameters
observerOrNextPartial<Observer<ObservableQuery.Result<MaybeMasked<TData>>>> | ((value: ObservableQuery.Result<MaybeMasked<TData>>) => void)Either an RxJS Observer with some or all callback methods,
or the next handler that is called for each value emitted from the subscribed Observable.
Update the variables of this observable query, and fetch the new results.
This method should be preferred over setVariables in most use cases.
Returns a ResultPromise with an additional .retain() method. Calling
.retain() keeps the network operation running even if the ObservableQuery
no longer requires the result.
Note: refetch() guarantees that a value will be emitted from the
observable, even if the result is deep equal to the previous value.
Signature
1refetch(
2 variables?: Partial<TVariables>
3): ObservableQuery.ResultPromise<ApolloClient.QueryResult<TData>>Parameters
The new set of variables. If there are missing variables, the previous values of those variables will be used.
A function that helps you fetch the next set of results for a paginated list field.
Signature
1fetchMore<TFetchData, TFetchVars>(
2 options: ObservableQuery.FetchMoreOptions<TData, TVariables, TFetchData, TFetchVars>
3): Promise<ApolloClient.QueryResult<TFetchData>>A function that enables you to execute a subscription, usually to subscribe to specific fields that were included in the query.
This function returns another function that you can call to terminate the subscription.
Signature
1subscribeToMore<TSubscriptionData, TSubscriptionVariables>(
2 options: ObservableQuery.SubscribeToMoreOptions<TData, TSubscriptionVariables, TSubscriptionData, TVariables>
3): () => voidTears down the ObservableQuery and stops all active operations by sending a complete notification.
Signature
1stop(): voidUpdate the variables of this observable query, and fetch the new results
if they've changed. Most users should prefer refetch instead of
setVariables in order to to be properly notified of results even when
they come from the cache.
Note: setVariables() guarantees that a value will be emitted from the
observable, even if the result is deeply equal to the previous value.
Note: the promise will resolve with the last emitted result when either the variables match the current variables or there are no subscribers to the query.
Signature
1setVariables(
2 variables: TVariables
3): Promise<ApolloClient.QueryResult<TData>>Parameters
The new set of variables. If there are missing variables, the previous values of those variables will be used.
A function that enables you to update the query's cached result without executing a followup GraphQL operation.
See using updateQuery and updateFragment for additional information.
Signature
1updateQuery(
2 mapFn: UpdateQueryMapFn<TData, TVariables>
3): voidA function that instructs the query to begin re-executing at a specified interval (in milliseconds).
Signature
1startPolling(
2 pollInterval: number
3): voidA function that instructs the query to stop polling after a previous call to startPolling.
Signature
1stopPolling(): voidReevaluate the query, optionally against new options. New options will be merged with the current options when given.
Note: variables can be reset back to their defaults (typically empty) by calling reobserve with
variables: undefined.
Signature
1reobserve(
2 newOptions?: Partial<ObservableQuery.Options<TData, TVariables>>
3): ObservableQuery.ResultPromise<ApolloClient.QueryResult<MaybeMasked<TData>>>Types
The current status of a query’s execution in our system.
No request is in flight for this query, but one or more errors were detected.
Indicates that fetchMore was called on this query and that the query created is currently in
flight.
The query has never been run before and the query is now currently running. A query will still have this network status even if a partial data result was returned from the cache, but a query was dispatched anyway.
Indicates that a polling query is currently in flight. So for example if you are polling a
query every 10 seconds then the network status will switch to poll every 10 seconds whenever
a poll request has been sent but not resolved.
No request is in flight for this query, and no errors happened. Everything is OK.
Similar to the setVariables network status. It means that refetch was called on a query
and the refetch request is currently in flight.
If setVariables was called and a query was fired because of that then the network status
will be setVariables until the result of that query comes back.
Indicates that a @defer query has received at least the first chunk of
the result but the full result has not yet been fully streamed to the
client.
DataValue.Complete<TData> | DataValue.Streaming<TData> | DataValue.Partial<TData> | undefinedAn object containing the result of your GraphQL query after it completes.
This value might be undefined if a query results in one or more errors (depending on the query's errorPolicy).
"complete" | "streaming" | "partial" | "empty"Describes the completeness of data.
empty: No data could be fulfilled from the cache or the result is incomplete.dataisundefined.partial: Some data could be fulfilled from the cache butdatais incomplete. This is only possible whenreturnPartialDataistrue.streaming:datais incomplete as a result of a deferred query and the result is still streaming in.complete:datais a fully satisfied query result fulfilled either from the cache or network.
ErrorLikeA single ErrorLike object describing the error that occured during the latest query execution.
For more information, see Handling operation errors.
boolean⚠️ Deprecated
This field will be removed in a future version of Apollo Client.
Describes whether data is a complete or partial result. This flag is only
set when returnPartialData is true in query options.
booleanIf true, the query is still in flight and results have not yet been returned.
NetworkStatusA number indicating the current network state of the query's associated request. See possible values.
Used in conjunction with the notifyOnNetworkStatusChange option.