@apollo/client
- Version 4.0.0
- Published
- 10.2 MB
- 7 dependencies
- MIT license
Install
npm i @apollo/client
yarn add @apollo/client
pnpm add @apollo/client
Overview
A fully-featured caching GraphQL client.
Index
Variables
Functions
Classes
ApolloClient
- cache
- clearStore()
- defaultContext
- defaultOptions
- devtoolsConfig
- disableNetworkFetches
- documentTransform
- extract()
- getMemoryInternals
- getObservableQueries()
- link
- localState
- mutate()
- onClearStore()
- onResetStore()
- prioritizeCacheValues
- query()
- queryDeduplication
- readFragment()
- readQuery()
- refetchObservableQueries()
- reFetchObservableQueries
- refetchQueries()
- resetStore()
- restore()
- setLink()
- stop()
- subscribe()
- version
- watchFragment()
- watchQuery()
- writeFragment()
- writeQuery()
Interfaces
Enums
Type Aliases
- ApolloClientOptions
- ApolloQueryResult
- DataState
- DefaultOptions
- DevtoolsOptions
- ErrorPolicy
- FetchPolicy
- GetDataState
- InternalRefetchQueriesInclude
- InternalRefetchQueriesMap
- InternalRefetchQueriesResult
- InternalRefetchQueryDescriptor
- MutateResult
- MutationFetchPolicy
- MutationOptions
- MutationQueryReducer
- MutationQueryReducersMap
- MutationUpdaterFunction
- NormalizedExecutionResult
- OnQueryUpdated
- OperationVariables
- QueryOptions
- RefetchQueriesInclude
- RefetchQueriesOptions
- RefetchQueriesPromiseResults
- RefetchQueriesResult
- RefetchQueryDescriptor
- RefetchWritePolicy
- SubscribeToMoreOptions
- SubscribeToMoreUpdateQueryFn
- SubscriptionOptions
- UpdateQueryOptions
- WatchQueryFetchPolicy
- WatchQueryOptions
Namespaces
Variables
Functions
function isNetworkRequestSettled
isNetworkRequestSettled: (networkStatus?: NetworkStatus) => boolean;
Returns true if the network request is in ready or error state according to a given network status.
Classes
class ApolloClient
class ApolloClient {}
This is the primary Apollo Client class. It is used to send GraphQL documents (i.e. queries and mutations) to a GraphQL spec-compliant server over an
ApolloLink
instance, receive results from the server and cache the results in a store. It also delivers updates to GraphQL queries throughObservable
instances.
constructor
constructor(options: ApolloClient.Options);
Constructs an instance of
ApolloClient
.Example 1
import { ApolloClient, InMemoryCache } from "@apollo/client";const cache = new InMemoryCache();const client = new ApolloClient({// Provide required constructor fieldscache: cache,uri: "http://localhost:4000/",// Provide some optional constructor fieldsname: "react-web-client",version: "1.3",queryDeduplication: false,defaultOptions: {watchQuery: {fetchPolicy: "cache-and-network",},},});
property cache
cache: ApolloCache;
property defaultContext
readonly defaultContext: Partial<DefaultContext>;
property defaultOptions
defaultOptions: ApolloClient.DefaultOptions;
property devtoolsConfig
readonly devtoolsConfig: ApolloClient.DevtoolsOptions;
property disableNetworkFetches
disableNetworkFetches: never;
Deprecated
disableNetworkFetches
has been renamed toprioritizeCacheValues
.
property documentTransform
readonly documentTransform: DocumentTransform;
The
DocumentTransform
used to modify GraphQL documents before a request is made. If a customDocumentTransform
is not provided, this will be the default document transform.
property getMemoryInternals
getMemoryInternals?: any;
This is not a stable API - it is used in development builds to expose information to the DevTools. Use at your own risk! For more details, see [Memory Management](https://www.apollographql.com/docs/react/caching/memory-management/#measuring-cache-usage)
Example 1
console.log(client.getMemoryInternals());Logs output in the following JSON format:
Example 2
{"limits": {"canonicalStringify": 1000,"print": 2000,"documentTransform.cache": 2000,"queryManager.getDocumentInfo": 2000,"PersistedQueryLink.persistedQueryHashes": 2000,"fragmentRegistry.transform": 2000,"fragmentRegistry.lookup": 1000,"fragmentRegistry.findFragmentSpreads": 4000,"cache.fragmentQueryDocuments": 1000,"removeTypenameFromVariables.getVariableDefinitions": 2000,"inMemoryCache.maybeBroadcastWatch": 5000,"inMemoryCache.executeSelectionSet": 10000,"inMemoryCache.executeSubSelectedArray": 5000},"sizes": {"canonicalStringify": 4,"print": 14,"addTypenameDocumentTransform": [{"cache": 14}],"queryManager": {"getDocumentInfo": 14,"documentTransforms": [{"cache": 14},{"cache": 14}]},"fragmentRegistry": {"findFragmentSpreads": 34,"lookup": 20,"transform": 14},"cache": {"fragmentQueryDocuments": 22},"inMemoryCache": {"executeSelectionSet": 4345,"executeSubSelectedArray": 1206,"maybeBroadcastWatch": 32},"links": [{"PersistedQueryLink": {"persistedQueryHashes": 14}},{"removeTypenameFromVariables": {"getVariableDefinitions": 14}}]}}Modifiers
@experimental
property link
link: ApolloLink;
property localState
localState: any;
The configured
LocalState
instance used to enable the use of@client
fields.
property prioritizeCacheValues
prioritizeCacheValues: boolean;
Whether to prioritize cache values over network results when
query
orwatchQuery
is called. This will essentially turn a"network-only"
or"cache-and-network"
fetchPolicy into a"cache-first"
fetchPolicy, but without influencing thefetchPolicy
of the createdObservableQuery
long-term.This can e.g. be used to prioritize the cache during the first render after SSR.
property queryDeduplication
queryDeduplication: boolean;
property reFetchObservableQueries
reFetchObservableQueries: ( includeStandby?: boolean) => Promise<ApolloClient.QueryResult<any>[]>;
Refetches all of your active queries.
reFetchObservableQueries()
is useful if you want to bring the client back to proper state in case of a network outageIt is important to remember that
reFetchObservableQueries()
_will_ refetch any active queries. This means that any components that might be mounted will execute their queries again using your network interface. If you do not want to re-execute any queries then you should make sure to stop watching any active queries. Takes optional parameterincludeStandby
which will include queries in standby-mode when refetching.Note:
cache-only
queries are not refetched by this function.Deprecated
Please use
refetchObservableQueries
instead.
property version
version: string;
method clearStore
clearStore: () => Promise<any[]>;
Remove all data from the store. Unlike
resetStore
,clearStore
will not refetch any active queries.
method extract
extract: (optimistic?: boolean) => unknown;
Exposes the cache's complete state, in a serializable format for later restoration.
method getObservableQueries
getObservableQueries: ( include?: RefetchQueriesInclude) => Set<ObservableQuery<any>>;
Get all currently active
ObservableQuery
objects, in aSet
.An "active" query is one that has observers and a
fetchPolicy
other than "standby" or "cache-only".You can include all
ObservableQuery
objects (including the inactive ones) by passing "all" instead of "active", or you can include just a subset of active queries by passing an array of query names or DocumentNode objects.Note: This method only returns queries that have active subscribers. Queries without subscribers are not tracked by the client.
method mutate
mutate: < TData = unknown, TVariables extends OperationVariables = OperationVariables, TCache extends ApolloCache = ApolloCache>( options: ApolloClient.MutateOptions<TData, TVariables, TCache>) => Promise<ApolloClient.MutateResult<MaybeMasked<TData>>>;
This resolves a single mutation according to the options specified and returns a Promise which is either resolved with the resulting data or rejected with an error. In some cases both
data
anderrors
might be undefined, for example whenerrorPolicy
is set to'ignore'
.It takes options as an object with the following keys and values:
method onClearStore
onClearStore: (cb: () => Promise<any>) => () => void;
Allows callbacks to be registered that are executed when the store is cleared.
onClearStore
returns an unsubscribe function that can be used to remove registered callbacks.
method onResetStore
onResetStore: (cb: () => Promise<any>) => () => void;
Allows callbacks to be registered that are executed when the store is reset.
onResetStore
returns an unsubscribe function that can be used to remove registered callbacks.
method query
query: < TData = unknown, TVariables extends OperationVariables = OperationVariables>( options: ApolloClient.QueryOptions<TData, TVariables>) => Promise<ApolloClient.QueryResult<MaybeMasked<TData>>>;
This resolves a single query according to the options specified and returns a
Promise
which is either resolved with the resulting data or rejected with an error.Parameter options
An object of type
QueryOptions
that allows us to describe how this query should be treated e.g. whether it should hit the server at all or just resolve from the cache, etc.
method readFragment
readFragment: { < TData = unknown, TVariables extends OperationVariables = OperationVariables >( options: ApolloClient.ReadFragmentOptions<TData, TVariables> ): Unmasked<TData> | null; < TData = unknown, TVariables extends OperationVariables = OperationVariables >( options: any, optimistic: boolean ): any;};
Tries to read some data from the store in the shape of the provided GraphQL fragment without making a network request. This method will read a GraphQL fragment from any arbitrary id that is currently cached, unlike
readQuery
which will only read from the root query.You must pass in a GraphQL document with a single fragment or a document with multiple fragments that represent what you are reading. If you pass in a document with multiple fragments then you must also specify a
fragmentName
.Parameter optimistic
Set to
true
to allowreadFragment
to return optimistic results. Isfalse
by default.Tries to read some data from the store in the shape of the provided GraphQL fragment without making a network request. This method will read a GraphQL fragment from any arbitrary id that is currently cached, unlike
readQuery
which will only read from the root query.You must pass in a GraphQL document with a single fragment or a document with multiple fragments that represent what you are reading. If you pass in a document with multiple fragments then you must also specify a
fragmentName
.Parameter optimistic
Set to
true
to allowreadFragment
to return optimistic results. Isfalse
by default.Deprecated
Pass the
optimistic
argument as part of the first argument instead of passing it as a separate option.
method readQuery
readQuery: { < TData = unknown, TVariables extends OperationVariables = OperationVariables >( options: ApolloClient.ReadQueryOptions<TData, TVariables> ): Unmasked<TData> | null; < TData = unknown, TVariables extends OperationVariables = OperationVariables >( options: any, optimistic: boolean ): any;};
Tries to read some data from the store in the shape of the provided GraphQL query without making a network request. This method will start at the root query. To start at a specific id returned by
cache.identify
usereadFragment
.Parameter optimistic
Set to
true
to allowreadQuery
to return optimistic results. Isfalse
by default.Tries to read some data from the store in the shape of the provided GraphQL query without making a network request. This method will start at the root query. To start at a specific id returned by
cache.identify
usereadFragment
.Parameter optimistic
Set to
true
to allowreadQuery
to return optimistic results. Isfalse
by default.Deprecated
Pass the
optimistic
argument as part of the first argument instead of passing it as a separate option.
method refetchObservableQueries
refetchObservableQueries: ( includeStandby?: boolean) => Promise<ApolloClient.QueryResult<any>[]>;
Refetches all of your active queries.
refetchObservableQueries()
is useful if you want to bring the client back to proper state in case of a network outageIt is important to remember that
refetchObservableQueries()
_will_ refetch any active queries. This means that any components that might be mounted will execute their queries again using your network interface. If you do not want to re-execute any queries then you should make sure to stop watching any active queries. Takes optional parameterincludeStandby
which will include queries in standby-mode when refetching.Note:
cache-only
queries are not refetched by this function.
method refetchQueries
refetchQueries: < TCache extends ApolloCache = ApolloCache, TResult = Promise<ApolloClient.QueryResult<any>>>( options: ApolloClient.RefetchQueriesOptions<TCache, TResult>) => ApolloClient.RefetchQueriesResult<TResult>;
Refetches specified active queries. Similar to "refetchObservableQueries()" but with a specific list of queries.
refetchQueries()
is useful for use cases to imperatively refresh a selection of queries.It is important to remember that
refetchQueries()
_will_ refetch specified active queries. This means that any components that might be mounted will execute their queries again using your network interface. If you do not want to re-execute any queries then you should make sure to stop watching any active queries.
method resetStore
resetStore: () => Promise<ApolloClient.QueryResult<any>[] | null>;
Resets your entire store by clearing out your cache and then re-executing all of your active queries. This makes it so that you may guarantee that there is no data left in your store from a time before you called this method.
resetStore()
is useful when your user just logged out. You’ve removed the user session, and you now want to make sure that any references to data you might have fetched while the user session was active is gone.It is important to remember that
resetStore()
_will_ refetch any active queries. This means that any components that might be mounted will execute their queries again using your network interface. If you do not want to re-execute any queries then you should make sure to stop watching any active queries.
method restore
restore: (serializedState: unknown) => ApolloCache;
Replaces existing state in the cache (if any) with the values expressed by
serializedState
.Called when hydrating a cache (server side rendering, or offline storage), and also (potentially) during hot reloads.
method setLink
setLink: (newLink: ApolloLink) => void;
Define a new ApolloLink (or link chain) that Apollo Client will use.
method stop
stop: () => void;
Call this method to terminate any active client processes, making it safe to dispose of this
ApolloClient
instance.This method performs aggressive cleanup to prevent memory leaks:
- Unsubscribes all active
ObservableQuery
instances by emitting acompleted
event - Rejects all currently running queries with "QueryManager stopped while query was in flight" - Removes all queryRefs from the suspense cache
method subscribe
subscribe: < TData = unknown, TVariables extends OperationVariables = OperationVariables>( options: ApolloClient.SubscribeOptions<TData, TVariables>) => SubscriptionObservable<ApolloClient.SubscribeResult<MaybeMasked<TData>>>;
This subscribes to a graphql subscription according to the options specified and returns an
Observable
which either emits received data or an error.
method watchFragment
watchFragment: < TData = unknown, TVariables extends OperationVariables = OperationVariables>( options: ApolloCache.WatchFragmentOptions<TData, TVariables>) => Observable<ApolloCache.WatchFragmentResult<TData>>;
Watches the cache store of the fragment according to the options specified and returns an
Observable
. We can subscribe to thisObservable
and receive updated results through an observer when the cache store changes.You must pass in a GraphQL document with a single fragment or a document with multiple fragments that represent what you are reading. If you pass in a document with multiple fragments then you must also specify a
fragmentName
.3.10.0
Parameter options
An object of type
WatchFragmentOptions
that allows the cache to identify the fragment and optionally specify whether to react to optimistic updates.
method watchQuery
watchQuery: < TData = unknown, TVariables extends OperationVariables = OperationVariables>( options: ApolloClient.WatchQueryOptions<TData, TVariables>) => ObservableQuery<TData, TVariables>;
This watches the cache store of the query according to the options specified and returns an
ObservableQuery
. We can subscribe to thisObservableQuery
and receive updated results through an observer when the cache store changes.Note that this method is not an implementation of GraphQL subscriptions. Rather, it uses Apollo's store in order to reactively deliver updates to your query results.
For example, suppose you call watchQuery on a GraphQL query that fetches a person's first and last name and this person has a particular object identifier, provided by
cache.identify
. Later, a different query fetches that same person's first and last name and the first name has now changed. Then, any observers associated with the results of the first query will be updated with a new result object.Note that if the cache does not change, the subscriber will _not_ be notified.
See [here](https://medium.com/apollo-stack/the-concepts-of-graphql-bc68bd819be3#.3mb0cbcmc) for a description of store reactivity.
method writeFragment
writeFragment: < TData = unknown, TVariables extends OperationVariables = OperationVariables>( options: ApolloClient.WriteFragmentOptions<TData, TVariables>) => Reference | undefined;
Writes some data in the shape of the provided GraphQL fragment directly to the store. This method will write to a GraphQL fragment from any arbitrary id that is currently cached, unlike
writeQuery
which will only write from the root query.You must pass in a GraphQL document with a single fragment or a document with multiple fragments that represent what you are writing. If you pass in a document with multiple fragments then you must also specify a
fragmentName
.
method writeQuery
writeQuery: < TData = unknown, TVariables extends OperationVariables = OperationVariables>( options: ApolloClient.WriteQueryOptions<TData, TVariables>) => Reference | undefined;
Writes some data in the shape of the provided GraphQL query directly to the store. This method will start at the root query. To start at a specific id returned by
cache.identify
then usewriteFragment
.
class ObservableQuery
class ObservableQuery< TData = unknown, TVariables extends OperationVariables = OperationVariables> implements Subscribable<ObservableQuery.Result<MaybeMasked<TData>>>, InteropObservable<ObservableQuery.Result<MaybeMasked<TData>>> {}
constructor
constructor({ queryManager, options, transformedQuery,}: { queryManager: QueryManager; options: ApolloClient.WatchQueryOptions<TData, TVariables>; transformedQuery?: DocumentNode | TypedDocumentNode<TData, TVariables>; queryId?: string;});
property ["@@observable"]
['@@observable']: () => Subscribable< ObservableQuery.Result< MaybeMasked<TData>, 'empty' | 'complete' | 'streaming' | 'partial' >>;
property [Symbol.observable]
[Symbol.observable]: () => Subscribable< ObservableQuery.Result< MaybeMasked<TData>, 'empty' | 'complete' | 'streaming' | 'partial' >>;
property options
readonly options: ObservableQuery.Options<TData, TVariables>;
property pipe
pipe: Observable< ObservableQuery.Result< MaybeMasked<TData>, 'empty' | 'complete' | 'streaming' | 'partial' >>;
Used to stitch together functional operators into a chain.
Returns
The Observable result of all the operators having been called in the order they were passed in.
Example 1
import { filter, map } from 'rxjs';observableQuery.pipe(filter(...),map(...),).subscribe(x => console.log(x));
property query
readonly query: TypedDocumentNode<TData, TVariables>;
property queryName
readonly queryName?: string;
property subscribe
subscribe: (observerOrNext: any) => Subscription;
Subscribes to the
ObservableQuery
.Parameter observerOrNext
Either an RxJS
Observer
with some or all callback methods, or thenext
handler that is called for each value emitted from the subscribed Observable.Returns
A subscription reference to the registered handlers.
property variables
readonly variables: OperationVariables;
An object containing the variables that were provided for the query.
method fetchMore
fetchMore: < TFetchData = TData, TFetchVars extends OperationVariables = TVariables>( options: ObservableQuery.FetchMoreOptions< TData, TVariables, TFetchData, TFetchVars >) => Promise<ApolloClient.QueryResult<TFetchData>>;
A function that helps you fetch the next set of results for a [paginated list field](https://www.apollographql.com/docs/react/pagination/core-api/).
method getCurrentResult
getCurrentResult: () => ObservableQuery.Result<MaybeMasked<TData>>;
method hasObservers
hasObservers: () => boolean;
method refetch
refetch: ( variables?: Partial<TVariables>) => ObservableQuery.ResultPromise<ApolloClient.QueryResult<TData>>;
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 theObservableQuery
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.Parameter variables
The new set of variables. If there are missing variables, the previous values of those variables will be used.
method reobserve
reobserve: ( newOptions?: Partial<ObservableQuery.Options<TData, TVariables>>) => ObservableQuery.ResultPromise<ApolloClient.QueryResult<MaybeMasked<TData>>>;
Reevaluate 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 callingreobserve
withvariables: undefined
.
method setVariables
setVariables: ( variables: TVariables) => Promise<ApolloClient.QueryResult<TData>>;
Update the variables of this observable query, and fetch the new results if they've changed. Most users should prefer
refetch
instead ofsetVariables
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.
Parameter variables
The new set of variables. If there are missing variables, the previous values of those variables will be used.
method startPolling
startPolling: (pollInterval: number) => void;
A function that instructs the query to begin re-executing at a specified interval (in milliseconds).
method stop
stop: () => void;
Tears down the
ObservableQuery
and stops all active operations by sending acomplete
notification.
method stopPolling
stopPolling: () => void;
A function that instructs the query to stop polling after a previous call to
startPolling
.
method subscribeToMore
subscribeToMore: < TSubscriptionData = TData, TSubscriptionVariables extends OperationVariables = TVariables>( options: ObservableQuery.SubscribeToMoreOptions< TData, TSubscriptionVariables, TSubscriptionData, TVariables >) => () => void;
A function that enables you to execute a [subscription](https://www.apollographql.com/docs/react/data/subscriptions/), 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.
method updateQuery
updateQuery: (mapFn: UpdateQueryMapFn<TData, TVariables>) => void;
A function that enables you to update the query's cached result without executing a followup GraphQL operation.
See [using updateQuery and updateFragment](https://www.apollographql.com/docs/react/caching/cache-interaction/#using-updatequery-and-updatefragment) for additional information.
Interfaces
interface DefaultContext
interface DefaultContext extends Record<string, any> {}
property clientAwareness
clientAwareness?: ClientAwarenessLink.ClientAwarenessOptions;
property queryDeduplication
queryDeduplication?: boolean;
Indicates whether
queryDeduplication
was enabled for the request.
interface ErrorLike
interface ErrorLike {}
Represents an
Error
type, but used throughout Apollo Client to represent errors that may otherwise failinstanceof
checks if they are cross-realm Error instances (see the [Error.isError
proposal](https://github.com/tc39/proposal-is-error) for more details).Apollo Client uses several types of errors throughout the client which can be narrowed using
instanceof
:-
CombinedGraphQLErrors
-errors
returned from a GraphQL result -CombinedProtocolErrors
- Transport-level errors from multipart subscriptions. -ServerParseError
- A JSON-parse error when parsing the server response. -ServerError
- A non-200 server response.Example 1
import { CombinedGraphQLErrors } from "@apollo/client";try {await client.query({ query });} catch (error) {// Use `instanceof` to check for more specific types of errors.if (error instanceof CombinedGraphQLErrors) {error.errors.map((graphQLError) => console.log(graphQLError.message));} else {console.error(errors);}}
interface InternalRefetchQueriesOptions
interface InternalRefetchQueriesOptions<TCache extends ApolloCache, TResult> extends Omit<ApolloClient.RefetchQueriesOptions<TCache, TResult>, 'include'> {}
property include
include?: InternalRefetchQueriesInclude;
property removeOptimistic
removeOptimistic?: string;
interface SubscribeToMoreFunction
interface SubscribeToMoreFunction< TData, TVariables extends OperationVariables = OperationVariables> {}
call signature
< TSubscriptionData = TData, TSubscriptionVariables extends OperationVariables = TVariables>( options: ObservableQuery.SubscribeToMoreOptions< TData, TSubscriptionVariables, TSubscriptionData, TVariables >): () => void;
interface SubscriptionObservable
interface SubscriptionObservable<T> extends Observable<T> {}
Observable created by initiating a subscription operation.
property restart
restart: () => void;
Used to restart the connection to the link chain. Calling this on a deduplicated subscription will restart the connection for all observables that share the request.
Example 1
const observable = client.subscribe({ query: subscription });observable.subscribe((value) => {// ...});observable.restart();
interface TypeOverrides
interface TypeOverrides {}
interface UpdateQueryMapFn
interface UpdateQueryMapFn< TData = unknown, TVariables extends OperationVariables = OperationVariables> {}
call signature
( /** * @deprecated This value is not type-safe and may contain partial data. This * argument will be removed in Apollo Client v5. Use `options.previousData` * instead for a more type-safe value. */ unsafePreviousData: DeepPartial<Unmasked<TData>>, options: UpdateQueryOptions<TData, TVariables>): Unmasked<TData> | void;
Enums
enum NetworkStatus
enum NetworkStatus { loading = 1, setVariables = 2, fetchMore = 3, refetch = 4, poll = 6, ready = 7, error = 8, streaming = 9,}
The current status of a query’s execution in our system.
member error
error = 8
No request is in flight for this query, but one or more errors were detected.
member fetchMore
fetchMore = 3
Indicates that
fetchMore
was called on this query and that the query created is currently in flight.
member loading
loading = 1
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.
member poll
poll = 6
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.
member ready
ready = 7
No request is in flight for this query, and no errors happened. Everything is OK.
member refetch
refetch = 4
Similar to the
setVariables
network status. It means thatrefetch
was called on a query and the refetch request is currently in flight.
member setVariables
setVariables = 2
If
setVariables
was called and a query was fired because of that then the network status will besetVariables
until the result of that query comes back.
member streaming
streaming = 9
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.
Type Aliases
type ApolloClientOptions
type ApolloClientOptions = ApolloClient.Options;
Deprecated
Use
ApolloClient.Options
instead
type ApolloQueryResult
type ApolloQueryResult< TData, TStates extends DataState<TData>['dataState'] = DataState<TData>['dataState']> = ObservableQuery.Result<TData, TStates>;
Deprecated
Use
ObservableQuery.Result
instead
type DataState
type DataState<TData> = | { /** * An 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`). * * @docGroup 1. Operation data */ data: DataValue.Complete<TData>; /** * Describes the completeness of `data`. * * - `empty`: No data could be fulfilled from the cache or the result is * incomplete. `data` is `undefined`. * - `partial`: Some data could be fulfilled from the cache but `data` is * incomplete. This is only possible when `returnPartialData` is `true`. * - `streaming`: `data` is incomplete as a result of a deferred query and * the result is still streaming in. * - `complete`: `data` is a fully satisfied query result fulfilled * either from the cache or network. * * @docGroup 1. Operation data */ dataState: 'complete'; } | { /** * An 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`). * * @docGroup 1. Operation data */ data: DataValue.Streaming<TData>; /** * Describes the completeness of `data`. * * - `empty`: No data could be fulfilled from the cache or the result is * incomplete. `data` is `undefined`. * - `partial`: Some data could be fulfilled from the cache but `data` is * incomplete. This is only possible when `returnPartialData` is `true`. * - `streaming`: `data` is incomplete as a result of a deferred query and * the result is still streaming in. * - `complete`: `data` is a fully satisfied query result fulfilled * either from the cache or network. * * @docGroup 1. Operation data */ dataState: 'streaming'; } | { /** * An 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`). * * @docGroup 1. Operation data */ data: DataValue.Partial<TData>; /** * Describes the completeness of `data`. * * - `empty`: No data could be fulfilled from the cache or the result is * incomplete. `data` is `undefined`. * - `partial`: Some data could be fulfilled from the cache but `data` is * incomplete. This is only possible when `returnPartialData` is `true`. * - `streaming`: `data` is incomplete as a result of a deferred query and * the result is still streaming in. * - `complete`: `data` is a fully satisfied query result fulfilled * either from the cache or network. * * @docGroup 1. Operation data */ dataState: 'partial'; } | { /** * An 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`). * * @docGroup 1. Operation data */ data: undefined; /** * Describes the completeness of `data`. * * - `empty`: No data could be fulfilled from the cache or the result is * incomplete. `data` is `undefined`. * - `partial`: Some data could be fulfilled from the cache but `data` is * incomplete. This is only possible when `returnPartialData` is `true`. * - `streaming`: `data` is incomplete as a result of a deferred query and * the result is still streaming in. * - `complete`: `data` is a fully satisfied query result fulfilled * either from the cache or network. * * @docGroup 1. Operation data */ dataState: 'empty'; };
type DefaultOptions
type DefaultOptions = ApolloClient.DefaultOptions;
Deprecated
Use
ApolloClient.DefaultOptions
instead
type DevtoolsOptions
type DevtoolsOptions = ApolloClient.DevtoolsOptions;
Deprecated
Use
ApolloClient.DevtoolsOptions
instead
type ErrorPolicy
type ErrorPolicy = 'none' | 'ignore' | 'all';
errorPolicy determines the level of events for errors in the execution result. The options are:
- none (default): any errors from the request are treated like runtime errors and the observable is stopped - ignore: errors from the request do not stop the observable, but also don't call
next
- all: errors are treated like data and will notify observables
type FetchPolicy
type FetchPolicy = 'cache-first' | 'network-only' | 'cache-only' | 'no-cache';
fetchPolicy determines where the client may return a result from. The options are:
- cache-first (default): return result from cache. Only fetch from network if cached result is not available. - cache-and-network: return result from cache first (if it exists), then return network result once it's available. - cache-only: return result from cache if available, fail otherwise. - no-cache: return result from network, fail if network call doesn't succeed, don't save to cache - network-only: return result from network, fail if network call doesn't succeed, save to cache - standby: only for queries that aren't actively watched, but should be available for refetch and updateQueries.
type GetDataState
type GetDataState<TData, TState extends DataState<TData>['dataState']> = Extract< DataState<TData>, { dataState: TState; }>;
type InternalRefetchQueriesInclude
type InternalRefetchQueriesInclude = | InternalRefetchQueryDescriptor[] | RefetchQueriesIncludeShorthand;
type InternalRefetchQueriesMap
type InternalRefetchQueriesMap<TResult> = Map< ObservableQuery<any>, InternalRefetchQueriesResult<TResult>>;
type InternalRefetchQueriesResult
type InternalRefetchQueriesResult<TResult> = TResult extends boolean ? Promise<ApolloClient.QueryResult<any>> : TResult;
type InternalRefetchQueryDescriptor
type InternalRefetchQueryDescriptor = | RefetchQueryDescriptor | ApolloClient.QueryOptions;
type MutateResult
type MutateResult<TData = unknown> = ApolloClient.MutateResult<TData>;
Deprecated
Use
ApolloClient.MutateResult
instead
type MutationFetchPolicy
type MutationFetchPolicy = Extract<FetchPolicy, 'network-only' | 'no-cache'>;
type MutationOptions
type MutationOptions< TData = unknown, TVariables extends OperationVariables = OperationVariables, TCache extends ApolloCache = ApolloCache> = ApolloClient.MutateOptions<TData, TVariables, TCache>;
Deprecated
Use
ApolloClient.MutateOptions
instead
type MutationQueryReducer
type MutationQueryReducer<T> = ( previousResult: Record<string, any>, options: { mutationResult: NormalizedExecutionResult<Unmasked<T>>; queryName: string | undefined; queryVariables: Record<string, any>; }) => Record<string, any>;
type MutationQueryReducersMap
type MutationQueryReducersMap< T = { [key: string]: any; }> = { [queryName: string]: MutationQueryReducer<T>;};
type MutationUpdaterFunction
type MutationUpdaterFunction< TData, TVariables extends OperationVariables, TCache extends ApolloCache> = ( cache: TCache, result: FormattedExecutionResult<Unmasked<TData>>, options: { context?: DefaultContext; variables?: TVariables; }) => void;
type NormalizedExecutionResult
type NormalizedExecutionResult< TData = Record<string, unknown>, TExtensions = Record<string, unknown>> = Omit<FormattedExecutionResult<TData, TExtensions>, 'data'> & GetDataState<TData, 'streaming' | 'complete'>;
Represents a result that might be complete or still streaming and has been normalized into a plain GraphQL result. When the result is still
streaming
, some fields might not yet be available.
type OnQueryUpdated
type OnQueryUpdated<TResult> = ( observableQuery: ObservableQuery<any>, diff: Cache.DiffResult<any>, lastDiff: Cache.DiffResult<any> | undefined) => boolean | TResult;
type OperationVariables
type OperationVariables = Record<string, any>;
type QueryOptions
type QueryOptions< TVariables extends OperationVariables = OperationVariables, TData = unknown> = ApolloClient.QueryOptions<TData, TVariables>;
Deprecated
Use
ApolloClient.QueryOptions
instead
type RefetchQueriesInclude
type RefetchQueriesInclude = | RefetchQueryDescriptor[] | RefetchQueriesIncludeShorthand;
type RefetchQueriesOptions
type RefetchQueriesOptions< TCache extends ApolloCache, TResult> = ApolloClient.RefetchQueriesOptions<TCache, TResult>;
Deprecated
Use
ApolloClient.RefetchQueriesOptions
instead
type RefetchQueriesPromiseResults
type RefetchQueriesPromiseResults<TResult> = IsAny<TResult> extends true ? any[] : TResult extends boolean ? ApolloClient.QueryResult<any>[] : TResult extends PromiseLike<infer U> ? U[] : TResult[];
type RefetchQueriesResult
type RefetchQueriesResult<TResult> = ApolloClient.RefetchQueriesResult<TResult>;
Deprecated
Use
ApolloClient.RefetchQueriesResult
instead
type RefetchQueryDescriptor
type RefetchQueryDescriptor = string | DocumentNode;
type RefetchWritePolicy
type RefetchWritePolicy = 'merge' | 'overwrite';
type SubscribeToMoreOptions
type SubscribeToMoreOptions< TData = unknown, TSubscriptionVariables extends OperationVariables = OperationVariables, TSubscriptionData = TData, TVariables extends OperationVariables = TSubscriptionVariables> = ObservableQuery.SubscribeToMoreOptions< TData, TSubscriptionVariables, TSubscriptionData, TVariables>;
Deprecated
Use
ObservableQuery.SubscribeToMoreOptions
instead
type SubscribeToMoreUpdateQueryFn
type SubscribeToMoreUpdateQueryFn< TData = unknown, TVariables extends OperationVariables = OperationVariables, TSubscriptionData = TData> = { ( /** * @deprecated This value is not type-safe and may contain partial data. This * argument will be removed in Apollo Client v5. Use `options.previousData` * instead for a more type-safe value. */ unsafePreviousData: DeepPartial<Unmasked<TData>>, options: UpdateQueryOptions<TData, TVariables> & { subscriptionData: { data: Unmasked<TSubscriptionData>; }; } ): Unmasked<TData> | void;};
type SubscriptionOptions
type SubscriptionOptions< TVariables extends OperationVariables = OperationVariables, TData = unknown> = ApolloClient.SubscribeOptions<TData, TVariables>;
Deprecated
Use
ApolloClient.SubscribeOptions
instead
type UpdateQueryOptions
type UpdateQueryOptions<TData, TVariables extends OperationVariables> = { variables?: TVariables;} & ( | { /** * Indicate if the previous query result has been found fully in the cache. */ complete: true; previousData: Unmasked<TData>; } | { /** * Indicate if the previous query result has not been found fully in the cache. * Might have partial or missing data. */ complete: false; previousData: DeepPartial<Unmasked<TData>> | undefined; });
type WatchQueryFetchPolicy
type WatchQueryFetchPolicy = FetchPolicy | 'cache-and-network' | 'standby';
type WatchQueryOptions
type WatchQueryOptions< TVariables extends OperationVariables = OperationVariables, TData = unknown> = ApolloClient.WatchQueryOptions<TData, TVariables>;
Deprecated
Use
ApolloClient.WatchQueryOptions
instead
Namespaces
namespace ApolloClient
namespace ApolloClient {}
interface DefaultOptions
interface DefaultOptions {}
property mutate
mutate?: Partial<ApolloClient.MutateOptions<any, any, any>>;
property query
query?: Partial<ApolloClient.QueryOptions<any, any>>;
property watchQuery
watchQuery?: Partial<ApolloClient.WatchQueryOptions<any, any>>;
interface DevtoolsOptions
interface DevtoolsOptions {}
property enabled
enabled?: boolean;
If
true
, the [Apollo Client Devtools](https://www.apollographql.com/docs/react/development-testing/developer-tooling/#apollo-client-devtools) browser extension can connect to thisApolloClient
instance.The default value is
false
in production andtrue
in development if there is awindow
object.
property name
name?: string;
Optional name for this
ApolloClient
instance in the devtools. This is useful when you instantiate multiple clients and want to be able to identify them by name.
interface MutateResult
interface MutateResult<TData = unknown> {}
property data
data: TData | undefined;
The data returned from your mutation. Can be
undefined
ifignoreResults
istrue
.
property error
error?: ErrorLike;
If the mutation produces one or more errors, this object contains either an array of
graphQLErrors
or a singlenetworkError
. Otherwise, this value isundefined
.For more information, see [Handling operation errors](https://www.apollographql.com/docs/react/data/error-handling/).
property extensions
extensions?: Record<string, unknown>;
Custom extensions returned from the GraphQL server
interface Options
interface Options {}
property assumeImmutableResults
assumeImmutableResults?: boolean;
If
true
, Apollo Client will assume results read from the cache are never mutated by application code, which enables substantial performance optimizations.
property cache
cache: ApolloCache;
The cache that Apollo Client should use to store query results locally. The recommended cache is
InMemoryCache
, which is provided by the@apollo/client
package.For more information, see [Configuring the cache](https://www.apollographql.com/docs/react/caching/cache-configuration/).
property clientAwareness
clientAwareness?: ClientAwarenessLink.ClientAwarenessOptions;
property dataMasking
dataMasking?: boolean;
Determines if data masking is enabled for the client.
property defaultContext
defaultContext?: Partial<DefaultContext>;
property defaultOptions
defaultOptions?: ApolloClient.DefaultOptions;
Provide this object to set application-wide default values for options you can provide to the
watchQuery
,query
, andmutate
functions. See below for an example object.See this [example object](https://www.apollographql.com/docs/react/api/core/ApolloClient#example-defaultoptions-object).
property devtools
devtools?: DevtoolsOptions;
Configuration used by the [Apollo Client Devtools extension](https://www.apollographql.com/docs/react/development-testing/developer-tooling/#apollo-client-devtools) for this client.
3.11.0
property documentTransform
documentTransform?: DocumentTransform;
property enhancedClientAwareness
enhancedClientAwareness?: ClientAwarenessLink.EnhancedClientAwarenessOptions;
property incrementalHandler
incrementalHandler?: Incremental.Handler<any>;
Determines the strategy used to parse incremental chunks from
@defer
queries.
property link
link: ApolloLink;
An
ApolloLink
instance to serve as Apollo Client's network layer. For more information, see [Advanced HTTP networking](https://www.apollographql.com/docs/react/networking/advanced-http-networking/).
property localState
localState?: LocalState;
property queryDeduplication
queryDeduplication?: boolean;
If
false
, Apollo Client sends every created query to the server, even if a _completely_ identical query (identical in terms of query string, variable values, and operationName) is already in flight.
property ssrForceFetchDelay
ssrForceFetchDelay?: number;
The time interval (in milliseconds) before Apollo Client force-fetches queries after a server-side render.
property ssrMode
ssrMode?: boolean;
When using Apollo Client for [server-side rendering](https://www.apollographql.com/docs/react/performance/server-side-rendering/), set this to
true
so that the [getDataFromTree
function](../react/ssr/#getdatafromtree) can work effectively.
interface QueryResult
interface QueryResult<TData = unknown> {}
property data
data: TData | undefined;
An 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'serrorPolicy
).1. Operation data
property error
error?: ErrorLike;
A single ErrorLike object describing the error that occured during the latest query execution.
For more information, see [Handling operation errors](https://www.apollographql.com/docs/react/data/error-handling/).
1. Operation data
interface RefetchQueriesOptions
interface RefetchQueriesOptions<TCache extends ApolloCache, TResult> {}
Options object for the
client.refetchQueries
method.
property include
include?: RefetchQueriesInclude;
Optional array specifying queries to refetch. Each element can be either a query's string name or a
DocumentNode
object.Pass
"active"
as a shorthand to refetch all active queries, or"all"
to refetch all active and inactive queries.Analogous to the [
options.refetchQueries
](https://www.apollographql.com/docs/react/data/mutations/#options) array for mutations.
property onQueryUpdated
onQueryUpdated?: OnQueryUpdated<TResult> | null;
Optional callback function that's called once for each
ObservableQuery
that's either affected byoptions.updateCache
or listed inoptions.include
(or both).If
onQueryUpdated
is not provided, the default implementation returns the result of callingobservableQuery.refetch()
. WhenonQueryUpdated
is provided, it can dynamically decide whether (and how) each query should be refetched.Returning
false
fromonQueryUpdated
prevents the associated query from being refetched.
property optimistic
optimistic?: boolean;
If
true
, theoptions.updateCache
function is executed on a temporary optimistic layer ofInMemoryCache
, so its modifications can be discarded from the cache after observing which fields it invalidated.Defaults to
false
, meaningoptions.updateCache
updates the cache in a lasting way.
property updateCache
updateCache?: (cache: TCache) => void;
Optional function that updates cached fields to trigger refetches of queries that include those fields.
interface RefetchQueriesResult
interface RefetchQueriesResult<TResult> extends Promise<RefetchQueriesPromiseResults<TResult>>, RefetchQueriesResult.AdditionalProperties<TResult> {}
The result of client.refetchQueries is thenable/awaitable, if you just want an array of fully resolved results, but you can also access the raw results immediately by examining the additional
queries
andresults
properties of theRefetchQueriesResult<TResult> object
.
interface SubscribeResult
interface SubscribeResult<TData = unknown> {}
property data
data: TData | undefined;
The data returned from your mutation. Can be
undefined
ifignoreResults
istrue
.
property error
error?: ErrorLike;
If the mutation produces one or more errors, this object contains either an array of
graphQLErrors
or a singlenetworkError
. Otherwise, this value isundefined
.For more information, see [Handling operation errors](https://www.apollographql.com/docs/react/data/error-handling/).
property extensions
extensions?: Record<string, unknown>;
Custom extensions returned from the GraphQL server
type MutateOptions
type MutateOptions< TData = unknown, TVariables extends OperationVariables = OperationVariables, TCache extends ApolloCache = ApolloCache> = { /** * By providing either an object or a callback function that, when invoked after * a mutation, allows you to return optimistic data and optionally skip updates * via the `IGNORE` sentinel object, Apollo Client caches this temporary * (and potentially incorrect) response until the mutation completes, enabling * more responsive UI updates. * * For more information, see [Optimistic mutation results](https://www.apollographql.com/docs/react/performance/optimistic-ui/). * * @docGroup 3. Caching options */ optimisticResponse?: | Unmasked<NoInfer<TData>> | (( vars: TVariables, { IGNORE, }: { IGNORE: IgnoreModifier; } ) => Unmasked<NoInfer<TData>> | IgnoreModifier); /** * A `MutationQueryReducersMap`, which is map from query names to * mutation query reducers. Briefly, this map defines how to incorporate the * results of the mutation into the results of queries that are currently * being watched by your application. */ updateQueries?: MutationQueryReducersMap<TData>; /** * An array (or a function that _returns_ an array) that specifies which queries you want to refetch after the mutation occurs. * * Each array value can be either: * * - An object containing the `query` to execute, along with any `variables` * * - A string indicating the operation name of the query to refetch * * @docGroup 1. Operation options */ refetchQueries?: | (( result: NormalizedExecutionResult<Unmasked<TData>> ) => InternalRefetchQueriesInclude) | InternalRefetchQueriesInclude; /** * If `true`, makes sure all queries included in `refetchQueries` are completed before the mutation is considered complete. * * The default value is `false` (queries are refetched asynchronously). * * @docGroup 1. Operation options */ awaitRefetchQueries?: boolean; /** * A function used to update the Apollo Client cache after the mutation completes. * * For more information, see [Updating the cache after a mutation](https://www.apollographql.com/docs/react/data/mutations#updating-the-cache-after-a-mutation). * * @docGroup 3. Caching options */ update?: MutationUpdaterFunction<TData, TVariables, TCache>; /** * Optional callback for intercepting queries whose cache data has been updated by the mutation, as well as any queries specified in the `refetchQueries: [...]` list passed to `client.mutate`. * * Returning a `Promise` from `onQueryUpdated` will cause the final mutation `Promise` to await the returned `Promise`. Returning `false` causes the query to be ignored. * * @docGroup 1. Operation options */ onQueryUpdated?: OnQueryUpdated<any>; /** * Specifies how the mutation handles a response that returns both GraphQL errors and partial results. * * For details, see [GraphQL error policies](https://www.apollographql.com/docs/react/data/error-handling/#graphql-error-policies). * * The default value is `none`, meaning that the mutation result includes error details but _not_ partial results. * * @docGroup 1. Operation options */ errorPolicy?: ErrorPolicy; /** * If you're using [Apollo Link](https://www.apollographql.com/docs/react/api/link/introduction/), this object is the initial value of the `context` object that's passed along your link chain. * * @docGroup 2. Networking options */ context?: DefaultContext; /** * Provide `no-cache` if the mutation's result should _not_ be written to the Apollo Client cache. * * The default value is `network-only` (which means the result _is_ written to the cache). * * Unlike queries, mutations _do not_ support [fetch policies](https://www.apollographql.com/docs/react/data/queries/#setting-a-fetch-policy) besides `network-only` and `no-cache`. * * @docGroup 3. Caching options */ fetchPolicy?: MutationFetchPolicy; /** * To avoid retaining sensitive information from mutation root field * arguments, Apollo Client v3.4+ automatically clears any `ROOT_MUTATION` * fields from the cache after each mutation finishes. If you need this * information to remain in the cache, you can prevent the removal by passing * `keepRootFields: true` to the mutation. `ROOT_MUTATION` result data are * also passed to the mutation `update` function, so we recommend obtaining * the results that way, rather than using this option, if possible. */ keepRootFields?: boolean; /** * A GraphQL document, often created with `gql` from the `graphql-tag` * package, that contains a single mutation inside of it. * * @docGroup 1. Operation options */ mutation: DocumentNode | TypedDocumentNode<TData, TVariables>;} & VariablesOption<NoInfer<TVariables>>;
type QueryOptions
type QueryOptions< TData = unknown, TVariables extends OperationVariables = OperationVariables> = { /** * A GraphQL query string parsed into an AST with the gql template literal. * * @docGroup 1. Operation options */ query: DocumentNode | TypedDocumentNode<TData, TVariables>; /** * Specifies how the query handles a response that returns both GraphQL errors and partial results. * * For details, see [GraphQL error policies](https://www.apollographql.com/docs/react/data/error-handling/#graphql-error-policies). * * The default value is `none`, meaning that the query result includes error details but not partial results. * * @docGroup 1. Operation options */ errorPolicy?: ErrorPolicy; /** * If you're using [Apollo Link](https://www.apollographql.com/docs/react/api/link/introduction/), this object is the initial value of the `context` object that's passed along your link chain. * * @docGroup 2. Networking options */ context?: DefaultContext; /** * Specifies how the query interacts with the Apollo Client cache during execution (for example, whether it checks the cache for results before sending a request to the server). * * For details, see [Setting a fetch policy](https://www.apollographql.com/docs/react/data/queries/#setting-a-fetch-policy). * * The default value is `cache-first`. * * @docGroup 3. Caching options */ fetchPolicy?: FetchPolicy;} & VariablesOption<NoInfer<TVariables>>;
Query options.
type ReadFragmentOptions
type ReadFragmentOptions< TData, TVariables extends OperationVariables> = Base.ReadFragmentOptions<TData, TVariables> & VariablesOption<TVariables>;
type ReadQueryOptions
type ReadQueryOptions< TData, TVariables extends OperationVariables> = Base.ReadQueryOptions<TData, TVariables> & VariablesOption<TVariables>;
type SubscribeOptions
type SubscribeOptions< TData = unknown, TVariables extends OperationVariables = OperationVariables> = { /** * A GraphQL document, often created with `gql` from the `graphql-tag` * package, that contains a single subscription inside of it. */ query: DocumentNode | TypedDocumentNode<TData, TVariables>; /** * How you want your component to interact with the Apollo cache. For details, see [Setting a fetch policy](https://www.apollographql.com/docs/react/data/queries/#setting-a-fetch-policy). */ fetchPolicy?: FetchPolicy; /** * Specifies the `ErrorPolicy` to be used for this operation */ errorPolicy?: ErrorPolicy; /** * Shared context between your component and your network interface (Apollo Link). */ context?: DefaultContext; /** * Shared context between your component and your network interface (Apollo Link). */ extensions?: Record<string, any>;} & VariablesOption<NoInfer<TVariables>>;
type WatchFragmentOptions
type WatchFragmentOptions< TData = unknown, TVariables extends OperationVariables = OperationVariables> = ApolloCache.WatchFragmentOptions<TData, TVariables>;
type WatchFragmentResult
type WatchFragmentResult<TData = unknown> = ApolloCache.WatchFragmentResult<TData>;
type WatchQueryOptions
type WatchQueryOptions< TData = unknown, TVariables extends OperationVariables = OperationVariables> = { /** * Specifies how the query interacts with the Apollo Client cache during execution (for example, whether it checks the cache for results before sending a request to the server). * * For details, see [Setting a fetch policy](https://www.apollographql.com/docs/react/data/queries/#setting-a-fetch-policy). * * The default value is `cache-first`. * * @docGroup 3. Caching options */ fetchPolicy?: WatchQueryFetchPolicy; /** * Specifies the `FetchPolicy` to be used after this query has completed. * * @docGroup 3. Caching options */ nextFetchPolicy?: | WatchQueryFetchPolicy | (( this: WatchQueryOptions<TData, TVariables>, currentFetchPolicy: WatchQueryFetchPolicy, context: NextFetchPolicyContext<TData, TVariables> ) => WatchQueryFetchPolicy); /** * Defaults to the initial value of options.fetchPolicy, but can be explicitly * configured to specify the WatchQueryFetchPolicy to revert back to whenever * variables change (unless nextFetchPolicy intervenes). * * @docGroup 3. Caching options */ initialFetchPolicy?: WatchQueryFetchPolicy; /** * Specifies whether a `NetworkStatus.refetch` operation should merge * incoming field data with existing data, or overwrite the existing data. * Overwriting is probably preferable, but merging is currently the default * behavior, for backwards compatibility with Apollo Client 3.x. * * @docGroup 3. Caching options */ refetchWritePolicy?: RefetchWritePolicy; /** * Specifies how the query handles a response that returns both GraphQL errors and partial results. * * For details, see [GraphQL error policies](https://www.apollographql.com/docs/react/data/error-handling/#graphql-error-policies). * * The default value is `none`, meaning that the query result includes error details but not partial results. * * @docGroup 1. Operation options */ errorPolicy?: ErrorPolicy; /** * If you're using [Apollo Link](https://www.apollographql.com/docs/react/api/link/introduction/), this object is the initial value of the `context` object that's passed along your link chain. * * @docGroup 2. Networking options */ context?: DefaultContext; /** * Specifies the interval (in milliseconds) at which the query polls for updated results. * * The default value is `0` (no polling). * * @docGroup 2. Networking options */ pollInterval?: number; /** * If `true`, the in-progress query's associated component re-renders whenever the network status changes or a network error occurs. * * The default value is `true`. * * @docGroup 2. Networking options */ notifyOnNetworkStatusChange?: boolean; /** * If `true`, the query can return partial results from the cache if the cache doesn't contain results for all queried fields. * * The default value is `false`. * * @docGroup 3. Caching options */ returnPartialData?: boolean; /** * A callback function that's called whenever a refetch attempt occurs * while polling. If the function returns `true`, the refetch is * skipped and not reattempted until the next poll interval. * * @docGroup 2. Networking options */ skipPollAttempt?: () => boolean; /** * A GraphQL query string parsed into an AST with the gql template literal. * * @docGroup 1. Operation options */ query: DocumentNode | TypedDocumentNode<TData, TVariables>;} & VariablesOption<NoInfer<TVariables>>;
Watched query options.
type WriteFragmentOptions
type WriteFragmentOptions< TData, TVariables extends OperationVariables> = Base.WriteFragmentOptions<TData, TVariables> & VariablesOption<TVariables>;
type WriteQueryOptions
type WriteQueryOptions< TData, TVariables extends OperationVariables> = Base.WriteQueryOptions<TData, TVariables> & VariablesOption<TVariables>;
namespace ApolloClient.Base
namespace ApolloClient.Base {}
interface ReadFragmentOptions
interface ReadFragmentOptions<TData, TVariables extends OperationVariables> {}
property fragment
fragment: DocumentNode | TypedDocumentNode<TData, TVariables>;
A GraphQL document created using the
gql
template string tag with one or more fragments which will be used to determine the shape of data to read. If you provide more than one fragment in this document then you must also specifyfragmentName
to specify which fragment is the root fragment.
property fragmentName
fragmentName?: string;
The name of the fragment in your GraphQL document to be used. If you do not provide a
fragmentName
and there is only one fragment in yourfragment
document then that fragment will be used.
property id
id?: string;
The root id to be used. This id should take the same form as the value returned by the
cache.identify
function. If a value with your id does not exist in the store,null
will be returned.
property optimistic
optimistic?: boolean;
Whether to read from optimistic or non-optimistic cache data. This option should be preferred over the
optimistic
parameter of thereadFragment
method.
property returnPartialData
returnPartialData?: boolean;
Whether to return incomplete data rather than null.
interface ReadQueryOptions
interface ReadQueryOptions<TData, TVariables extends OperationVariables> {}
property id
id?: string;
The root id to be used. Defaults to "ROOT_QUERY", which is the ID of the root query object. This property makes
readQuery
capable of reading data from any object in the cache.
property optimistic
optimistic?: boolean;
Whether to read from optimistic or non-optimistic cache data. This option should be preferred over the
optimistic
parameter of thereadQuery
method.
property query
query: DocumentNode | TypedDocumentNode<TData, TVariables>;
The GraphQL query shape to be used constructed using the
gql
template string tag. The query will be used to determine the shape of the data to be read.
property returnPartialData
returnPartialData?: boolean;
Whether to return incomplete data rather than null.
interface WriteFragmentOptions
interface WriteFragmentOptions<TData, TVariables extends OperationVariables> {}
property broadcast
broadcast?: boolean;
Whether to notify query watchers.
property data
data: Unmasked<TData>;
The data to write to the store.
property fragment
fragment: DocumentNode | TypedDocumentNode<TData, TVariables>;
A GraphQL document created using the
gql
template string tag fromgraphql-tag
with one or more fragments which will be used to determine the shape of data to read. If you provide more than one fragment in this document then you must also specifyfragmentName
to specify which fragment is the root fragment.
property fragmentName
fragmentName?: string;
The name of the fragment in your GraphQL document to be used. If you do not provide a
fragmentName
and there is only one fragment in yourfragment
document then that fragment will be used.
property id
id?: string;
The root id to be used. This id should take the same form as the value returned by the
cache.identify
function. If a value with your id does not exist in the store,null
will be returned.
property overwrite
overwrite?: boolean;
When true, ignore existing field data rather than merging it with incoming data.
interface WriteQueryOptions
interface WriteQueryOptions<TData, TVariables extends OperationVariables> {}
property broadcast
broadcast?: boolean;
Whether to notify query watchers.
property data
data: Unmasked<TData>;
The data to write to the store.
property id
id?: string;
The root id to be used. Defaults to "ROOT_QUERY", which is the ID of the root query object. This property makes writeQuery capable of writing data to any object in the cache.
property overwrite
overwrite?: boolean;
When true, ignore existing field data rather than merging it with incoming data.
property query
query: DocumentNode | TypedDocumentNode<TData, TVariables>;
The GraphQL query shape to be used constructed using the
gql
template string tag. The query will be used to determine the shape of the data to be read.
namespace ApolloClient.DocumentationTypes
namespace ApolloClient.DocumentationTypes {}
interface ReadQueryOptions
interface ReadQueryOptions<TData, TVariables extends OperationVariables> extends Base.ReadQueryOptions<TData, TVariables> {}
property variables
variables?: TVariables;
Any variables that the GraphQL query may depend on.
interface WriteFragmentOptions
interface WriteFragmentOptions<TData, TVariables extends OperationVariables> extends Base.WriteFragmentOptions<TData, TVariables> {}
property variables
variables?: TVariables;
Any variables that your GraphQL fragments depend on.
interface WriteQueryOptions
interface WriteQueryOptions<TData, TVariables extends OperationVariables> extends Base.WriteQueryOptions<TData, TVariables> {}
property variables
variables?: TVariables;
Any variables that your GraphQL fragments depend on.
interface WriteQueryOptions
interface WriteQueryOptions<TData, TVariables extends OperationVariables> extends Base.WriteQueryOptions<TData, TVariables> {}
property variables
variables?: TVariables;
Any variables that the GraphQL query may depend on.
namespace ApolloClient.RefetchQueriesResult
namespace ApolloClient.RefetchQueriesResult {}
interface AdditionalProperties
interface AdditionalProperties<TResult> {}
property queries
queries: ObservableQuery<any>[];
An array of ObservableQuery objects corresponding 1:1 to TResult values in the results arrays (both the
result
property and the resolved value).
property results
results: InternalRefetchQueriesResult<TResult>[];
An array of results that were either returned by
onQueryUpdated
, or provided by default in the absence ofonQueryUpdated
, including pending promises.If
onQueryUpdated
returnsfalse
for a given query, no result is provided for that query.If
onQueryUpdated
returnstrue
, the resultingPromise<ApolloQueryResult<any>>
is included in theresults
array instead oftrue
.
namespace DataValue
namespace DataValue {}
type Complete
type Complete<TData> = ApplyHKTImplementationWithDefault< TypeOverrides, 'Complete', OverridableTypes.Defaults, TData>;
Returns a representation of
TData
in it's "complete" state.Example 1
You can override this type globally - this example shows how to override it with
DeepPartial<TData>
:import { HKT, DeepPartial } from "@apollo/client/utilities";type CompleteOverride<TData> =TData extends { _complete?: infer _Complete } ? _Complete : TData;interface CompleteOverrideHKT extends HKT {return: CompleteOverride<this["arg1"]>;}declare module "@apollo/client" {export interface TypeOverrides {Complete: CompleteOverrideHKT;}}
type Partial
type Partial<TData> = ApplyHKTImplementationWithDefault< TypeOverrides, 'Partial', OverridableTypes.Defaults, TData>;
Returns a representation of
TData
while it is partial.Example 1
You can override this type globally - this example shows how to override it with
DeepPartial<TData>
:import { HKT, DeepPartial } from "@apollo/client/utilities";type PartialOverride<TData> = DeepPartial<Complete<TData>>;interface PartialOverrideHKT extends HKT {return: PartialOverride<this["arg1"]>;}declare module "@apollo/client" {export interface TypeOverrides {Partial: PartialOverrideHKT;}}
type Streaming
type Streaming<TData> = ApplyHKTImplementationWithDefault< TypeOverrides, 'Streaming', OverridableTypes.Defaults, TData>;
Returns a representation of
TData
while it is streaming.Example 1
You can override this type globally - this example shows how to override it with
DeepPartial<TData>
:import { HKT, DeepPartial } from "@apollo/client/utilities";type StreamingOverride<TData> = DeepPartial<TData>;interface StreamingOverrideHKT extends HKT {return: StreamingOverride<this["arg1"]>;}declare module "@apollo/client" {export interface TypeOverrides {Streaming: StreamingOverrideHKT;}}
namespace InternalTypes
namespace InternalTypes {}
class QueryManager
class QueryManager {}
constructor
constructor(options: QueryManagerOptions);
property assumeImmutableResults
readonly assumeImmutableResults: boolean;
property cache
readonly cache: ApolloCache;
property client
readonly client: ApolloClient;
property clientOptions
readonly clientOptions: ApolloClient.Options;
The options that were passed to the ApolloClient constructor.
property dataMasking
readonly dataMasking: boolean;
property defaultContext
readonly defaultContext: Partial<DefaultContext>;
property defaultOptions
defaultOptions: ApolloClient.DefaultOptions;
property documentTransform
readonly documentTransform: DocumentTransform;
property fetchCancelFns
protected fetchCancelFns: Map<string, (error: any) => any>;
property incrementalHandler
readonly incrementalHandler: Incremental.Handler;
property inFlightLinkObservables
protected inFlightLinkObservables: Trie<{ observable?: Observable<ApolloLink.Result<any>>; restart?: () => void;}>;
property link
readonly link: ApolloLink;
property localState
localState: any;
property mutationStore
mutationStore?: { [mutationId: string]: MutationStoreValue };
property obsQueries
obsQueries: Set<ObservableQuery<any, any>>;
All ObservableQueries that currently have at least one subscriber.
property prioritizeCacheValues
prioritizeCacheValues: boolean;
Whether to prioritize cache values over network results when
fetchObservableWithInfo
is called. This will essentially turn a"network-only"
or"cache-and-network"
fetchPolicy into a"cache-first"
fetchPolicy, but without influencing thefetchPolicy
of theObservableQuery
.This can e.g. be used to prioritize the cache during the first render after SSR.
property ssrMode
readonly ssrMode: boolean;
method broadcastQueries
broadcastQueries: () => void;
method clearStore
clearStore: (options?: Cache.ResetOptions) => Promise<void>;
method fetchObservableWithInfo
fetchObservableWithInfo: <TData, TVariables extends OperationVariables>( options: ApolloClient.WatchQueryOptions<TData, TVariables>, { networkStatus, query, fetchQueryOperator, onCacheHit, observableQuery, }: { networkStatus?: NetworkStatus; query?: DocumentNode; fetchQueryOperator?: <T>(source: Observable<T>) => Observable<T>; onCacheHit?: () => void; observableQuery?: ObservableQuery<TData, TVariables> | undefined; }) => ObservableAndInfo<TData>;
method fetchQuery
fetchQuery: <TData, TVariables extends OperationVariables>( options: ApolloClient.WatchQueryOptions<TData, TVariables>, networkStatus?: NetworkStatus) => Promise<ApolloClient.QueryResult<TData>>;
method generateRequestId
generateRequestId: () => number;
method getDocumentInfo
getDocumentInfo: (document: DocumentNode) => TransformCacheEntry;
method getObservableQueries
getObservableQueries: ( include?: InternalRefetchQueriesInclude) => Set<ObservableQuery<any, OperationVariables>>;
method getVariables
getVariables: <TVariables extends OperationVariables>( document: DocumentNode, variables?: TVariables) => TVariables;
method maskFragment
maskFragment: <TData = unknown>(options: MaskFragmentOptions<TData>) => TData;
method maskOperation
maskOperation: <TData = unknown>( options: MaskOperationOptions<TData>) => MaybeMasked<TData>;
method mutate
mutate: < TData, TVariables extends OperationVariables, TCache extends ApolloCache>({ mutation, variables, optimisticResponse, updateQueries, refetchQueries, awaitRefetchQueries, update: updateWithProxyFn, onQueryUpdated, fetchPolicy, errorPolicy, keepRootFields, context,}: ApolloClient.MutateOptions<TData, TVariables, TCache> & { errorPolicy: ErrorPolicy; fetchPolicy: MutationFetchPolicy;}) => Promise<ApolloClient.MutateResult<MaybeMasked<TData>>>;
method query
query: <TData, TVariables extends OperationVariables = OperationVariables>( options: ApolloClient.QueryOptions<TData, TVariables>) => Promise<ApolloClient.QueryResult<MaybeMasked<TData>>>;
method refetchObservableQueries
refetchObservableQueries: ( includeStandby?: boolean) => Promise<ApolloClient.QueryResult<any>[]>;
method refetchQueries
refetchQueries: <TResult>({ updateCache, include, optimistic, removeOptimistic, onQueryUpdated,}: InternalRefetchQueriesOptions< ApolloCache, TResult>) => InternalRefetchQueriesMap<TResult>;
method startGraphQLSubscription
startGraphQLSubscription: <TData = unknown>( options: ApolloClient.SubscribeOptions<TData>) => SubscriptionObservable<ApolloClient.SubscribeResult<TData>>;
method stop
stop: () => void;
Call this method to terminate any active query processes, making it safe to dispose of this QueryManager instance.
method transform
transform: (document: DocumentNode) => DocumentNode;
method watchQuery
watchQuery: <TData, TVariables extends OperationVariables = OperationVariables>( options: ApolloClient.WatchQueryOptions<TData, TVariables>) => ObservableQuery<TData, TVariables>;
interface NextFetchPolicyContext
interface NextFetchPolicyContext<TData, TVariables extends OperationVariables> {}
property initialFetchPolicy
initialFetchPolicy: WatchQueryFetchPolicy;
property observable
observable: ObservableQuery<TData, TVariables>;
property options
options: ApolloClient.WatchQueryOptions<TData, TVariables>;
property reason
reason: 'after-fetch' | 'variables-changed';
namespace ObservableQuery
namespace ObservableQuery {}
interface ResultPromise
interface ResultPromise<T> extends Promise<T> {}
Promise returned by
reobserve
andrefetch
methods.By default, if the
ObservableQuery
is not interested in the result of this operation anymore, the network operation will be cancelled.This has an additional
retain
method that can be used to keep the network operation running until it is finished nonetheless.
method retain
retain: () => this;
Kepp the network operation running until it is finished, even if
ObservableQuery
unsubscribed from the operation.
interface SubscribeToMoreOptions
interface SubscribeToMoreOptions< TData = unknown, TSubscriptionVariables extends OperationVariables = OperationVariables, TSubscriptionData = TData, TVariables extends OperationVariables = TSubscriptionVariables> {}
property context
context?: DefaultContext;
property document
document: | DocumentNode | TypedDocumentNode<TSubscriptionData, TSubscriptionVariables>;
property onError
onError?: (error: ErrorLike) => void;
property updateQuery
updateQuery?: SubscribeToMoreUpdateQueryFn<TData, TVariables, TSubscriptionData>;
property variables
variables?: TSubscriptionVariables;
type FetchMoreOptions
type FetchMoreOptions< TData, TVariables extends OperationVariables, TFetchData = TData, TFetchVars extends OperationVariables = TVariables> = { /** * A GraphQL query string parsed into an AST with the gql template literal. * * @docGroup 1. Operation options */ query?: DocumentNode | TypedDocumentNode<TFetchData, TFetchVars>; /** * An object containing all of the GraphQL variables your query requires to execute. * * Each key in the object corresponds to a variable name, and that key's value corresponds to the variable value. * * @docGroup 1. Operation options */ variables?: Partial<NoInfer<TFetchVars>>; /** * Specifies how the query handles a response that returns both GraphQL errors and partial results. * * For details, see [GraphQL error policies](https://www.apollographql.com/docs/react/data/error-handling/#graphql-error-policies). * * The default value is `none`, meaning that the query result includes error details but not partial results. * * @docGroup 1. Operation options */ errorPolicy?: ErrorPolicy; /** * If you're using [Apollo Link](https://www.apollographql.com/docs/react/api/link/introduction/), this object is the initial value of the `context` object that's passed along your link chain. * * @docGroup 2. Networking options */ context?: DefaultContext; updateQuery?: ( previousQueryResult: Unmasked<TData>, options: { fetchMoreResult: Unmasked<TFetchData>; variables: TFetchVars; } ) => Unmasked<TData>;};
type Options
type Options< TData = unknown, TVariables extends OperationVariables = OperationVariables> = { /** * Specifies how the query interacts with the Apollo Client cache during execution (for example, whether it checks the cache for results before sending a request to the server). * * For details, see [Setting a fetch policy](https://www.apollographql.com/docs/react/data/queries/#setting-a-fetch-policy). * * The default value is `cache-first`. * * @docGroup 3. Caching options */ fetchPolicy: WatchQueryFetchPolicy; /** * Specifies the `FetchPolicy` to be used after this query has completed. * * @docGroup 3. Caching options */ nextFetchPolicy?: | WatchQueryFetchPolicy | (( this: ApolloClient.WatchQueryOptions<TData, TVariables>, currentFetchPolicy: WatchQueryFetchPolicy, context: NextFetchPolicyContext<TData, TVariables> ) => WatchQueryFetchPolicy); /** * Defaults to the initial value of options.fetchPolicy, but can be explicitly * configured to specify the WatchQueryFetchPolicy to revert back to whenever * variables change (unless nextFetchPolicy intervenes). * * @docGroup 3. Caching options */ initialFetchPolicy: WatchQueryFetchPolicy; /** * Specifies whether a `NetworkStatus.refetch` operation should merge * incoming field data with existing data, or overwrite the existing data. * Overwriting is probably preferable, but merging is currently the default * behavior, for backwards compatibility with Apollo Client 3.x. * * @docGroup 3. Caching options */ refetchWritePolicy?: RefetchWritePolicy; /** * Specifies how the query handles a response that returns both GraphQL errors and partial results. * * For details, see [GraphQL error policies](https://www.apollographql.com/docs/react/data/error-handling/#graphql-error-policies). * * The default value is `none`, meaning that the query result includes error details but not partial results. * * @docGroup 1. Operation options */ errorPolicy?: ErrorPolicy; /** * If you're using [Apollo Link](https://www.apollographql.com/docs/react/api/link/introduction/), this object is the initial value of the `context` object that's passed along your link chain. * * @docGroup 2. Networking options */ context?: DefaultContext; /** * Specifies the interval (in milliseconds) at which the query polls for updated results. * * The default value is `0` (no polling). * * @docGroup 2. Networking options */ pollInterval?: number; /** * If `true`, the in-progress query's associated component re-renders whenever the network status changes or a network error occurs. * * The default value is `true`. * * @docGroup 2. Networking options */ notifyOnNetworkStatusChange?: boolean; /** * If `true`, the query can return partial results from the cache if the cache doesn't contain results for all queried fields. * * The default value is `false`. * * @docGroup 3. Caching options */ returnPartialData?: boolean; /** * A callback function that's called whenever a refetch attempt occurs * while polling. If the function returns `true`, the refetch is * skipped and not reattempted until the next poll interval. * * @docGroup 2. Networking options */ skipPollAttempt?: () => boolean; /** * A GraphQL query string parsed into an AST with the gql template literal. * * @docGroup 1. Operation options */ query: DocumentNode | TypedDocumentNode<TData, TVariables>; /** * An object containing all of the GraphQL variables your query requires to execute. * * Each key in the object corresponds to a variable name, and that key's value corresponds to the variable value. * * @docGroup 1. Operation options */ variables: TVariables;};
type Result
type Result< TData, TStates extends DataState<TData>['dataState'] = DataState<TData>['dataState']> = { /** * A single ErrorLike object describing the error that occured during the latest * query execution. * * For more information, see [Handling operation errors](https://www.apollographql.com/docs/react/data/error-handling/). * * @docGroup 1. Operation data */ error?: ErrorLike; /** * If `true`, the query is still in flight. * * @docGroup 2. Network info */ loading: boolean; /** * A number indicating the current network state of the query's associated request. [See possible values.](https://github.com/apollographql/apollo-client/blob/d96f4578f89b933c281bb775a39503f6cdb59ee8/src/core/networkStatus.ts#L4) * * Used in conjunction with the [`notifyOnNetworkStatusChange`](#notifyonnetworkstatuschange) option. * * @docGroup 2. Network info */ networkStatus: NetworkStatus; /** * Describes whether `data` is a complete or partial result. This flag is only * set when `returnPartialData` is `true` in query options. * * @deprecated This field will be removed in a future version of Apollo Client. * @docGroup 1. Operation data */ partial: boolean;} & GetDataState<TData, TStates>;
namespace ObservableQuery.DocumentationTypes
namespace ObservableQuery.DocumentationTypes {}
interface ObservableMethods
interface ObservableMethods<TData, OperatorResult> {}
method pipe
pipe: () => Observable<OperatorResult>;
Used to stitch together functional operators into a chain.
Returns
The Observable result of all the operators having been called in the order they were passed in.
Example 1
import { filter, map } from 'rxjs';observableQuery.pipe(filter(...),map(...),).subscribe(x => console.log(x));
method subscribe
subscribe: (observerOrNext: any) => Subscription;
Subscribes to the
ObservableQuery
.Parameter observerOrNext
Either an RxJS
Observer
with some or all callback methods, or thenext
handler that is called for each value emitted from the subscribed Observable.Returns
A subscription reference to the registered handlers.
type OperatorFunctionChain
type OperatorFunctionChain<From, To> = [];
Package Files (9)
Dependencies (7)
Dev Dependencies (0)
No dev dependencies.
Peer Dependencies (6)
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/@apollo/client
.
- Markdown[](https://www.jsdocs.io/package/@apollo/client)
- HTML<a href="https://www.jsdocs.io/package/@apollo/client"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 9148 ms. - Missing or incorrect documentation? Open an issue for this package.