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
1 import { ApolloClient, InMemoryCache } from '@apollo/client';
2
3 const cache = new InMemoryCache();
4
5 const client = new ApolloClient({
6 // Provide required constructor fields
7 cache: cache,
8 uri: 'http://localhost:4000/',
9
10 // Provide some optional constructor fields
11 name: 'react-web-client',
12 version: '1.3',
13 queryDeduplication: false,
14 defaultOptions: {
15 watchQuery: {
16 fetchPolicy: 'cache-and-network',
17 },
18 },
19 });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
1watchQuery<T, TVariables>(
2 options: WatchQueryOptions<TVariables, T>
3): ObservableQuery<T, TVariables>Parameters
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
1query<T, TVariables>(
2 options: QueryOptions<TVariables, T>
3): Promise<InteropApolloQueryResult<MaybeMasked<T>>>Parameters
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.
Result
Promise<InteropApolloQueryResult<MaybeMasked<T>>>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 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
1mutate<TData, TVariables, TContext, TCache>(
2 options: MutationOptions<TData, TVariables, TContext>
3): Promise<InteropMutateResult<MaybeMasked<TData>>>Parameters
Result
Promise<InteropMutateResult<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.
Signature
1subscribe<T, TVariables>(
2 options: SubscriptionOptions<TVariables, T>
3): Observable<InteropSubscribeResult<MaybeMasked<T>>>Parameters
Result
Observable<InteropSubscribeResult<MaybeMasked<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
1readQuery<T, TVariables>(
2 options: DataProxy.Query<TVariables, T>,
3 optimistic?: boolean
4): Unmasked<T> | nullParameters
Show/hide child attributes
stringThe 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.
DocumentNode | TypedDocumentNode<TData, TVariables>The GraphQL query shape to be used constructed using the gql template string tag from graphql-tag. The query will be used to determine the shape of the data to be read.
TVariablesAny variables that the GraphQL query may depend on.
Set to true to allow readQuery to return optimistic results. Is false by default.
Result
Unmasked<T> | nullTries 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
1readFragment<T, TVariables>(
2 options: DataProxy.Fragment<TVariables, T>,
3 optimistic?: boolean
4): Unmasked<T> | nullParameters
Show/hide child attributes
DocumentNode | TypedDocumentNode<TData, TVariables>A GraphQL document created using the gql template string tag from graphql-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 specify fragmentName to select a single.
stringThe 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 your fragment document then that fragment will be used.
stringThe root id to be used. This id should take the same form as the value returned by your dataIdFromObject function. If a value with your id does not exist in the store, null will be returned.
TVariablesAny variables that your GraphQL fragments depend on.
Set to true to allow readFragment to return optimistic results. Is false by default.
Result
Unmasked<T> | nullWrites 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
1writeQuery<TData, TVariables>(
2 options: DataProxy.WriteQueryOptions<TData, TVariables>
3): Reference | undefinedParameters
Show/hide child attributes
booleanWhether to notify query watchers (default: true).
Unmasked<TData>The data you will be writing to the store.
stringThe 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.
booleanWhen true, ignore existing field data rather than merging it with incoming data (default: false).
DocumentNode | TypedDocumentNode<TData, TVariables>The GraphQL query shape to be used constructed using the gql template string tag from graphql-tag. The query will be used to determine the shape of the data to be read.
TVariablesAny variables that the GraphQL query may depend on.
Result
Reference | undefinedWrites 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
1writeFragment<TData, TVariables>(
2 options: DataProxy.WriteFragmentOptions<TData, TVariables>
3): Reference | undefinedParameters
Show/hide child attributes
booleanWhether to notify query watchers (default: true).
Unmasked<TData>The data you will be writing to the store.
DocumentNode | TypedDocumentNode<TData, TVariables>A GraphQL document created using the gql template string tag from graphql-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 specify fragmentName to select a single.
stringThe 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 your fragment document then that fragment will be used.
stringThe root id to be used. This id should take the same form as the value returned by your dataIdFromObject function. If a value with your id does not exist in the store, null will be returned.
booleanWhen true, ignore existing field data rather than merging it with incoming data (default: false).
TVariablesAny variables that your GraphQL fragments depend on.
Result
Reference | undefinedwatchFragmentRequires ≥ 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
1watchFragment<TFragmentData, TVariables>(
2 options: WatchFragmentOptions<TFragmentData, TVariables>
3): Observable<WatchFragmentResult<TFragmentData>>Parameters
An object of type WatchFragmentOptions that allows the cache to identify the fragment and optionally specify whether to react to optimistic updates.
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
1resetStore(): Promise<InteropApolloQueryResult<any>[] | null>Result
Promise<InteropApolloQueryResult<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
1onResetStore(
2 cb: () => Promise<any>
3): () => voidParameters
Result
() => voidRemove all data from the store. Unlike resetStore, clearStore will not refetch any active queries.
Signature
1clearStore(): 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
1onClearStore(
2 cb: () => Promise<any>
3): () => voidParameters
Result
() => voidCall this method to terminate any active client processes, making it safe to dispose of this ApolloClient instance.
Signature
1stop(): voidRefetches 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
1reFetchObservableQueries(
2 includeStandby?: boolean
3): Promise<InteropApolloQueryResult<any>[]>Parameters
Result
Promise<InteropApolloQueryResult<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
1refetchQueries<TCache, TResult>(
2 options: RefetchQueriesOptions<TCache, TResult>
3): RefetchQueriesResult<TResult>Parameters
Result
RefetchQueriesResult<TResult>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
1getObservableQueries(
2 include?: RefetchQueriesInclude
3): Map<string, ObservableQuery<any>>Parameters
Result
Map<string, ObservableQuery<any>>Types
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 | UriFunction⚠️ Deprecated
uriwill be removed in Apollo Client 4.0.Recommended now
Instantiate an instance of
HttpClientand passurias an option.JavaScript1import { HttpLink } from "@apollo/client"; 2 3new ApolloClient({ 4 link: new HttpLink({ uri }) 5});
The 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.
boolean⚠️ Deprecated
connectToDevToolswill be removed in Apollo Client 4.0.Recommended now
Use the
devtools.enabledoption instead.TypeScript1new ApolloClient({ 2 devtools: { enabled: true } 3});
If 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.
string⚠️ Deprecated
namehas been moved toclientAwareness.namein Apollo Client 4.0.Recommended now
Use
clientAwareness.nameto set the client awareness name.TypeScript1new ApolloClient({ clientAwareness: { name } });
A 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.
string⚠️ Deprecated
namehas been moved toclientAwareness.versionin Apollo Client 4.0.Recommended now
Use
clientAwareness.versionto set the client awareness version.TypeScript1new ApolloClient({ clientAwareness: { version } });
A 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.
{
name?: string;
version?: string;
}booleanDetermines if data masking is enabled for the client.
Partial<DefaultContext>devtools(optional)Requires ≥ 3.11.0
DevtoolsOptionsConfiguration used by the Apollo Client Devtools extension for this client.
DocumentTransformbooleanIf 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.
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⚠️ Deprecated
credentialswill be removed in Apollo Client 4.0.Recommended now
Instantiate an instance of
HttpClientand passcredentialsas an option.JavaScript1import { HttpLink } from "@apollo/client"; 2 3new ApolloClient({ 4 link: new HttpLink({ credentials }) 5});
FragmentMatcher⚠️ Deprecated
Custom fragment matchers will no longer be supported in Apollo Client 4.0 and has been replaced by
cache.fragmentMatches. It is safe to continue using this in Apollo Client 3.x.Recommended now
No action needed
When upgrading
Leverage
possibleTypeswithInMemoryCacheto ensure fragments match correctly. EnsurepossibleTypesinclude local types if needed. This option should then be removed. If working with a 3rd party cache implementation, ensure the 3rd party cache implements thecache.fragmentMatchesmethod.
Record<string, string>⚠️ Deprecated
headerswill be removed in Apollo Client 4.0.Recommended now
Instantiate an instance of
HttpClientand passheadersas an option.JavaScript1import { HttpLink } from "@apollo/client"; 2 3new ApolloClient({ 4 link: new HttpLink({ headers }) 5});
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.
Resolvers | Resolvers[]⚠️ Deprecated
resolvershas been moved in Apollo Client 4.0. This option is safe to use in Apollo Client 3.x.Recommended now
No action needed
When upgrading
resolverswill need to be passed as theresolversoption to an instance ofLocalState. ThatLocalStateinstance should be provided as thelocalStateoption to theApolloClientconstructor.
string | string[] | DocumentNode | DocumentNode[]⚠️ Deprecated
typeDefswill be removed in Apollo Client 4.0. It is safe to stop using this option in Apollo Client 3.x.
Partial<MutationOptions<any, any, any>>Partial<QueryOptions<any, any>>Partial<WatchQueryOptions<any, any>>Example defaultOptions object
1const defaultOptions = {
2 watchQuery: {
3 fetchPolicy: 'cache-and-network',
4 errorPolicy: 'ignore',
5 },
6 query: {
7 fetchPolicy: 'network-only',
8 errorPolicy: 'all',
9 },
10 mutate: {
11 errorPolicy: 'all',
12 },
13};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
useQueryhook uses Apollo Client'swatchQueryfunction. To setdefaultOptionswhen using theuseQueryhook, make sure to set them under thedefaultOptions.watchQueryproperty.