class ApolloClient
API reference
The ApolloClient class encapsulates Apollo's core client-side API. It backs all available view-layer integrations (React, iOS, and so on).
The ApolloClient constructor
Constructs an instance of ApolloClient.
Takes an ApolloClientOptions parameter that supports the fields listed below.
Returns an initialized ApolloClient object.
Example
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',},},});
For more information on the defaultOptions object, see the Default Options section below.
Functions
This watches the cache store of the query according to the options specified and returns an ObservableQuery. We can subscribe to this ObservableQuery 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 dataIdFromObject. 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 for a description of store reactivity.
Signature
function watchQuery(options: WatchQueryOptions<TVariables, T>): ObservableQuery<T, TVariables>
Parameters
options
WatchQueryOptions<TVariables, T>Show/hide child attributes
ErrorPolicySpecifies how the query handles a response that returns both GraphQL errors and partial results.
For details, see GraphQL error policies.
The default value is none, meaning that the query result includes error details but not partial results.
DocumentNode | TypedDocumentNode<T, TVariables>A GraphQL query string parsed into an AST with the gql template literal.
TVariablesAn 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.
DefaultContextIf you're using Apollo Link, this object is the initial value of the context object that's passed along your link chain.
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 false.
numberSpecifies the interval (in milliseconds) at which the query polls for updated results.
The default value is 0 (no polling).
() => booleanA 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.
WatchQueryFetchPolicySpecifies 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.
The default value is cache-first.
WatchQueryFetchPolicyDefaults 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).
WatchQueryFetchPolicy | ((this: WatchQueryOptions<TVariables, T>, currentFetchPolicy: WatchQueryFetchPolicy, context: NextFetchPolicyContext<T, TVariables>) => WatchQueryFetchPolicy)Specifies the FetchPolicy to be used after this query has completed.
RefetchWritePolicySpecifies 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.
booleanIf 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.
boolean⚠️ Deprecated
Using canonizeResults can result in memory leaks so we generally do not recommend using this option anymore. A future version of Apollo Client will contain a similar feature without the risk of memory leaks.
Whether to canonize cache results before returning them. Canonization takes some extra time, but it speeds up future deep equality comparisons. Defaults to false.
boolean⚠️ Deprecated
Setting this option is unnecessary in Apollo Client 3, thanks to a more consistent application of fetch policies. It might be removed in a future release.
If true, causes a query refetch if the query result is detected as partial.
The default value is false.
Result
ObservableQuery<T, TVariables>
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.
Signature
function query(options: QueryOptions<TVariables, T>): Promise<ApolloQueryResult<T>>
Parameters
options
QueryOptions<TVariables, T>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.
Show/hide child attributes
ErrorPolicySpecifies how the query handles a response that returns both GraphQL errors and partial results.
For details, see GraphQL error policies.
The default value is none, meaning that the query result includes error details but not partial results.
DocumentNode | TypedDocumentNode<T, TVariables>A GraphQL query string parsed into an AST with the gql template literal.
TVariablesAn 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.
DefaultContextIf you're using Apollo Link, this object is the initial value of the context object that's passed along your link chain.
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 false.
numberSpecifies the interval (in milliseconds) at which the query polls for updated results.
The default value is 0 (no polling).
FetchPolicySpecifies 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.
The default value is cache-first.
booleanIf 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.
boolean⚠️ Deprecated
Using canonizeResults can result in memory leaks so we generally do not recommend using this option anymore. A future version of Apollo Client will contain a similar feature without the risk of memory leaks.
Whether to canonize cache results before returning them. Canonization takes some extra time, but it speeds up future deep equality comparisons. Defaults to false.
boolean⚠️ Deprecated
Setting this option is unnecessary in Apollo Client 3, thanks to a more consistent application of fetch policies. It might be removed in a future release.
If true, causes a query refetch if the query result is detected as partial.
The default value is false.
Result
Promise<ApolloQueryResult<T>>
Show/hide child attributes
TApolloErrorThe single Error object that is passed to onError and useQuery hooks, and is often thrown during manual client.query calls. This will contain both a NetworkError field and any GraphQLErrors. See https://www.apollographql.com/docs/react/data/error-handling/ for more information.
ReadonlyArray<GraphQLError>A list of any errors that occurred during server-side execution of a GraphQL operation. See https://www.apollographql.com/docs/react/data/error-handling/ for more information.
booleanNetworkStatusbooleanThis 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 and errors might be undefined, for example when errorPolicy is set to 'ignore'.
It takes options as an object with the following keys and values:
Signature
function mutate(options: MutationOptions<TData, TVariables, TContext>): Promise<FetchResult<TData>>
Parameters
options
MutationOptions<TData, TVariables, TContext>Show/hide child attributes
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).
ErrorPolicySpecifies how the mutation handles a response that returns both GraphQL errors and partial results.
For details, see GraphQL error policies.
The default value is none, meaning that the mutation result includes error details but not partial results.
DocumentNode | TypedDocumentNode<TData, TVariables>A GraphQL document, often created with gql from the graphql-tag package, that contains a single mutation inside of it.
OnQueryUpdated<any>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.
((result: FetchResult<TData>) => InternalRefetchQueriesInclude) | InternalRefetchQueriesIncludeAn 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
queryto execute, along with anyvariablesA string indicating the operation name of the query to refetch
TVariablesAn object containing all of the GraphQL variables your mutation requires to execute.
Each key in the object corresponds to a variable name, and that key's value corresponds to the variable value.
TContextIf you're using Apollo Link, this object is the initial value of the context object that's passed along your link chain.
MutationFetchPolicyProvide 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 besides network-only and no-cache.
TData | ((vars: TVariables, { IGNORE }: {
IGNORE: IgnoreModifier;
}) => TData)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.
MutationUpdaterFunction<TData, TVariables, TContext, TCache>A function used to update the Apollo Client cache after the mutation completes.
For more information, see Updating the cache after a mutation.
booleanTo 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.
MutationQueryReducersMap<TData>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.
Result
Promise<FetchResult<TData>>
This subscribes to a graphql subscription according to the options specified and returns an Observable which either emits received data or an error.
Signature
function subscribe(options: SubscriptionOptions<TVariables, T>): Observable<FetchResult<T>>
Parameters
options
SubscriptionOptions<TVariables, T>Show/hide child attributes
DefaultContextShared context between your component and your network interface (Apollo Link).
ErrorPolicySpecifies the ErrorPolicy to be used for this operation
FetchPolicyHow you want your component to interact with the Apollo cache. For details, see Setting a fetch policy.
DocumentNode | TypedDocumentNode<T, TVariables>A GraphQL document, often created with gql from the graphql-tag package, that contains a single subscription inside of it.
TVariablesAn object containing all of the variables your subscription needs to execute
Result
Observable<FetchResult<T>>
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 dataIdFromObject use readFragment.
Signature
function readQuery(options: DataProxy.Query<TVariables, T>,optimistic?: boolean): T | null
Parameters
options
DataProxy.Query<TVariables, T>optimistic (optional)
booleanSet to true to allow readQuery to return optimistic results. Is false by default.
Result
T | null
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.
Signature
function readFragment(options: DataProxy.Fragment<TVariables, T>,optimistic?: boolean): T | null
Parameters
options
DataProxy.Fragment<TVariables, T>optimistic (optional)
booleanSet to true to allow readFragment to return optimistic results. Is false by default.
Result
T | null
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 dataIdFromObject then use writeFragment.
Signature
function writeQuery(options: DataProxy.WriteQueryOptions<TData, TVariables>): Reference | undefined
Parameters
Result
Reference | undefined
Show/hide child attributes
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.
Signature
function writeFragment(options: DataProxy.WriteFragmentOptions<TData, TVariables>): Reference | undefined
Parameters
Result
Reference | undefined
Show/hide child attributes
watchFragmentSince 3.10.0
Watches the cache store of the fragment according to the options specified and returns an Observable. We can subscribe to this Observable 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.
Signature
function watchFragment(options: WatchFragmentOptions<TFragmentData, TVariables>): Observable<WatchFragmentResult<TFragmentData>>
Parameters
options
WatchFragmentOptions<TFragmentData, TVariables>An object of type WatchFragmentOptions that allows the cache to identify the fragment and optionally specify whether to react to optimistic updates.
Show/hide child attributes
DocumentNode | TypedDocumentNode<TFragmentData, TVariables>A GraphQL fragment document parsed into an AST with the gql template literal.
StoreObject | Reference | stringAn object containing a __typename and primary key fields (such as id) identifying the entity object from which the fragment will be retrieved, or a { __ref: "..." } reference, or a string ID (uncommon).
stringThe name of the fragment defined in the fragment document.
Required if the fragment document includes more than one fragment, optional otherwise.
booleanIf true, watchFragment returns optimistic results.
The default value is true.
TVariablesAny variables that the GraphQL fragment may depend on.
boolean⚠️ Deprecated
Using canonizeResults can result in memory leaks so we generally do not recommend using this option anymore. A future version of Apollo Client will contain a similar feature.
Whether to canonize cache results before returning them. Canonization takes some extra time, but it speeds up future deep equality comparisons. Defaults to false.
Result
Observable<WatchFragmentResult<TFragmentData>>
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.
Signature
function resetStore(): Promise<ApolloQueryResult<any>[] | null>
Result
Promise<ApolloQueryResult<any>[] | null>
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.
Signature
function onResetStore(cb: () => Promise<any>): () => void
Parameters
Result
() => void
Remove all data from the store. Unlike resetStore, clearStore will not refetch any active queries.
Signature
function clearStore(): Promise<any[]>
Result
Promise<any[]>
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.
Signature
function onClearStore(cb: () => Promise<any>): () => void
Parameters
Result
() => void
Call this method to terminate any active client processes, making it safe to dispose of this ApolloClient instance.
Signature
function stop(): void
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 outage
It 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 parameter includeStandby which will include queries in standby-mode when refetching.
Signature
function reFetchObservableQueries(includeStandby?: boolean): Promise<ApolloQueryResult<any>[]>
Parameters
Result
Promise<ApolloQueryResult<any>[]>
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.
Signature
function refetchQueries(options: RefetchQueriesOptions<TCache, TResult>): RefetchQueriesResult<TResult>
Parameters
options
RefetchQueriesOptions<TCache, TResult>Show/hide child attributes
RefetchQueriesIncludeOnQueryUpdated<TResult> | nullboolean(cache: TCache) => voidResult
RefetchQueriesResult<TResult>
Show/hide child attributes
(Warning: some properties might be missing from the table due to complex inheritance!)
Get all currently active ObservableQuery objects, in a Map keyed by query ID strings.
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.
Signature
function getObservableQueries(include?: RefetchQueriesInclude): Map<string, ObservableQuery<any>>
Parameters
Result
Map<string, ObservableQuery<any>>
Types
Properties
ApolloCache<TCacheShape>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.
ApolloLinkYou can provide an ApolloLink instance to serve as Apollo Client's network layer. For more information, see Advanced HTTP networking.
One of uri or link is required. If you provide both, link takes precedence.
string | UriFunctionThe URI of the GraphQL endpoint that Apollo Client will communicate with.
One of uri or link is required. If you provide both, link takes precedence.
booleanIf true, the Apollo Client Devtools browser extension can connect to Apollo Client.
The default value is false in production and true in development (if there is a window object).
DefaultOptionsProvide this object to set application-wide default values for options you can provide to the watchQuery, query, and mutate functions. See below for an example object.
See this example object.
stringA custom name (e.g., iOS) that identifies this particular client among your set of clients. Apollo Server and Apollo Studio use this property as part of the client awareness feature.
stringA custom version that identifies the current version of this particular client (e.g., 1.2). Apollo Server and Apollo Studio use this property as part of the client awareness feature.
This is not the version of Apollo Client that you are using, but rather any version string that helps you differentiate between versions of your client.
If true, Apollo Client will assume results read from the cache are never mutated by application code, which enables substantial performance optimizations.
stringPartial<DefaultContext>DocumentTransformFragmentMatcherRecord<string, string>An object representing headers to include in every HTTP request, such as {Authorization: 'Bearer 1234'}
This value will be ignored when using the link option.
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.
Resolvers | Resolvers[]The time interval (in milliseconds) before Apollo Client force-fetches queries after a server-side render.
booleanWhen using Apollo Client for server-side rendering, set this to true so that the getDataFromTree function can work effectively.
string | string[] | DocumentNode | DocumentNode[]Properties
Partial<MutationOptions<any, any, any>>Partial<QueryOptions<any, any>>Partial<WatchQueryOptions<any, any>>Example defaultOptions object
const defaultOptions = {watchQuery: {fetchPolicy: 'cache-and-network',errorPolicy: 'ignore',},query: {fetchPolicy: 'network-only',errorPolicy: 'all',},mutate: {errorPolicy: 'all',},};
You can override any default option you specify in this object by providing a different value for the same option in individual function calls.
Note: The useQuery hook uses Apollo Client's watchQuery function. To set defaultOptions when using the useQuery hook, make sure to set them under the defaultOptions.watchQuery property.