Docs
Launch GraphOS Studio

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 fields
cache: cache,
uri: 'http://localhost:4000/',
// Provide some optional constructor fields
name: '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

watchQuery(options): ObservableQuery<T, TVariables>

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 a GraphQL observer when the cache store changes.

Note that this method is not an implementation of GraphQL s. 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.

Parameters
Name / Type
Description
options
WatchQueryOptions<TVariables, T>
Show/hide child attributes
options.canonizeResults (optional)
boolean

Whether to canonize cache results before returning them. Canonization takes some extra time, but it speeds up future deep equality comparisons. Defaults to false.

options.context (optional)
DefaultContext

Context to be passed to link execution chain

options.errorPolicy (optional)
ErrorPolicy

Specifies the ErrorPolicy to be used for this query

options.fetchPolicy (optional)
WatchQueryFetchPolicy

Specifies the FetchPolicy to be used for this query.

options.initialFetchPolicy (optional)
WatchQueryFetchPolicy

Defaults to the initial value of options.fetchPolicy, but can be explicitly configured to specify the WatchQueryFetchPolicy to revert back to whenever s change (unless nextFetchPolicy intervenes).

options.nextFetchPolicy (optional)
WatchQueryFetchPolicy | ((this: WatchQueryOptions<TVariables, TData>, currentFetchPolicy: WatchQueryFetchPolicy, context: NextFetchPolicyContext<TData, TVariables>) => WatchQueryFetchPolicy)

Specifies the FetchPolicy to be used after this query has completed.

options.notifyOnNetworkStatusChange (optional)
boolean

Whether or not updates to the network status should trigger next on the observer of this query

options.partialRefetch (optional)
boolean

If true, perform a query refetch if the query result is marked as being partial, and the returned data is reset to an empty Object by the Apollo Client QueryManager (due to a cache miss).

options.pollInterval (optional)
number

The time interval (in milliseconds) on which this query should be refetched from the server.

options.query
DocumentNode | TypedDocumentNode<TData, TVariables>

A GraphQL document that consists of a single query to be sent down to the server.

options.refetchWritePolicy (optional)
RefetchWritePolicy

Specifies whether a {@link NetworkStatus.refetch} should merge incoming 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.

options.returnPartialData (optional)
boolean

Allow returning incomplete data from the cache when a larger query cannot be fully satisfied by the cache, instead of returning nothing.

options.variables (optional)
TVariables

A map going from name to variable value, where the variables are used within the GraphQL query.

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.

Parameters
Name / Type
Description
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
options.canonizeResults (optional)
boolean

Whether to canonize cache results before returning them. Canonization takes some extra time, but it speeds up future deep equality comparisons. Defaults to false.

options.context (optional)
DefaultContext

Context to be passed to link execution chain

options.errorPolicy (optional)
ErrorPolicy

Specifies the ErrorPolicy to be used for this query

options.fetchPolicy (optional)
FetchPolicy

Specifies the FetchPolicy to be used for this query

options.notifyOnNetworkStatusChange (optional)
boolean

Whether or not updates to the network status should trigger next on the observer of this query

options.partialRefetch (optional)
boolean

If true, perform a query refetch if the query result is marked as being partial, and the returned data is reset to an empty Object by the Apollo Client QueryManager (due to a cache miss).

options.pollInterval (optional)
number

The time interval (in milliseconds) on which this query should be refetched from the server.

options.query
DocumentNode | TypedDocumentNode<TData, TVariables>

A GraphQL document that consists of a single query to be sent down to the server.

options.returnPartialData (optional)
boolean

Allow returning incomplete data from the cache when a larger query cannot be fully satisfied by the cache, instead of returning nothing.

options.variables (optional)
TVariables

A map going from name to variable value, where the variables are used within the GraphQL query.

This resolves a single according to the options specified and returns a Promise which is either resolved with the resulting data or rejected with an error.

It takes options as an object with the following keys and values:

Parameters
Name / Type
Description
options
MutationOptions<TData, TVariables, TContext>
Show/hide child attributes
options.awaitRefetchQueries (optional)
boolean

By default, refetchQueries does not wait for the refetched queries to be completed, before resolving the Promise. This ensures that query refetching does not hold up response handling (query refetching is handled asynchronously). Set awaitRefetchQueries to true if you would like to wait for the refetched queries to complete, before the can be marked as resolved.

options.context (optional)
TContext

The context to be passed to the link execution chain. This context will only be used with this . It will not be used with refetchQueries. Refetched queries use the context they were initialized with (since the initial context is stored as part of the ObservableQuery instance). If a specific context is needed when refetching queries, make sure it is configured (via the query context option) when the query is first initialized/run.

options.errorPolicy (optional)
ErrorPolicy

Specifies the ErrorPolicy to be used for this

options.fetchPolicy (optional)
MutationFetchPolicy

Specifies the MutationFetchPolicy to be used for this query. s support only 'network-only' and 'no-cache' fetchPolicy strings. If fetchPolicy is not provided, it defaults to 'network-only'.

options.keepRootFields (optional)
boolean

To avoid retaining sensitive information from root s, Apollo Client v3.4+ automatically clears any ROOT_MUTATION s from the cache after each finishes. If you need this information to remain in the cache, you can prevent the removal by passing keepRootFields: true to the . ROOT_MUTATION result data are also passed to the update function, so we recommend obtaining the results that way, rather than using this option, if possible.

options.mutation
DocumentNode | TypedDocumentNode<TData, TVariables>

A GraphQL document, often created with gql from the graphql-tag package, that contains a single inside of it.

options.onQueryUpdated (optional)
OnQueryUpdated<any>

A function that will be called for each ObservableQuery affected by this , after the mutation has completed.

options.optimisticResponse (optional)
TData | ((vars: TVariables) => TData)

An object that represents the result of this that will be optimistically stored before the server has actually returned a result. This is most often used for optimistic UI, where we want to be able to see the result of a mutation immediately, and update the UI later if any errors appear.

options.refetchQueries (optional)
((result: FetchResult<TData>) => InternalRefetchQueriesInclude) | InternalRefetchQueriesInclude

A list of query names which will be refetched once this has returned. This is often used if you have a set of queries which may be affected by a mutation and will have to update. Rather than writing a mutation query reducer (i.e. updateQueries) for this, you can simply refetch the queries that will be affected and achieve a consistent store once these queries return.

options.update (optional)
MutationUpdaterFunction<TData, TVariables, TContext, TCache>

A function which provides an ApolloCache instance, and the result of the , to allow the user to update the store based on the results of the mutation.

This function will be called twice over the lifecycle of a . Once at the very beginning if an optimisticResponse was provided. The writes created from the optimistic data will be rolled back before the second time this function is called which is when the has successfully resolved. At that point update will be called with the actual result and those writes will not be rolled back.

Note that since this function is intended to be used to update the store, it cannot be used with a no-cache fetch policy. If you're interested in performing some action after a has completed, and you don't need to update the store, use the Promise returned from client.mutate instead.

options.updateQueries (optional)
MutationQueryReducersMap<TData>

A MutationQueryReducersMap, which is map from query names to 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.

options.variables (optional)
TVariables

An object that maps from the name of a as used in the GraphQL document to that variable's value.

This subscribes to a graphql according to the options specified and returns an Observable which either emits received data or an error.

Parameters
Name / Type
Description
options
SubscriptionOptions<TVariables, T>
Show/hide child attributes
options.context (optional)
DefaultContext

Context object to be passed through the link execution chain.

options.errorPolicy (optional)
ErrorPolicy

Specifies the ErrorPolicy to be used for this

options.fetchPolicy (optional)
FetchPolicy

Specifies the FetchPolicy to be used for this .

options.query
DocumentNode | TypedDocumentNode<TData, TVariables>

A GraphQL document, often created with gql from the graphql-tag package, that contains a single inside of it.

options.variables (optional)
TVariables

An object that maps from the name of a as used in the GraphQL document to that variable's value.

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.

Parameters
Name / Type
Description
options
DataProxy.Query<TVariables, T>
Show/hide child attributes
options.id (optional)
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.

options.query
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.

options.variables (optional)
TVariables

Any s that the GraphQL query may depend on.

optimistic (optional)
boolean

Set to true to allow readQuery to return optimistic results. Is false by default.

Tries to read some data from the store in the shape of the provided GraphQL 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 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.

Parameters
Name / Type
Description
options
DataProxy.Fragment<TVariables, T>
Show/hide child attributes
options.fragment
DocumentNode | TypedDocumentNode<TData, TVariables>

A GraphQL document created using the gql template string tag from graphql-tag with one or more s 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.

options.fragmentName (optional)
string

The name of the in your GraphQL document to be used. If you do not provide a fragmentName and there is only one in your fragment document then that will be used.

options.id (optional)
string

The 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.

options.variables (optional)
TVariables

Any s that your GraphQL s depend on.

optimistic (optional)
boolean

Set to true to allow readFragment to return optimistic results. Is false by default.

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.

Parameters
Name / Type
Description
options
DataProxy.WriteQueryOptions<TData, TVariables>
Show/hide child attributes
options.broadcast (optional)
boolean

Whether to notify query watchers (default: true).

options.data
TData

The data you will be writing to the store.

options.id (optional)
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.

options.overwrite (optional)
boolean

When true, ignore existing data rather than merging it with incoming data (default: false).

options.query
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.

options.variables (optional)
TVariables

Any s that the GraphQL query may depend on.

Writes some data in the shape of the provided GraphQL 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 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.

Parameters
Name / Type
Description
options
DataProxy.WriteFragmentOptions<TData, TVariables>
Show/hide child attributes
options.broadcast (optional)
boolean

Whether to notify query watchers (default: true).

options.data
TData

The data you will be writing to the store.

options.fragment
DocumentNode | TypedDocumentNode<TData, TVariables>

A GraphQL document created using the gql template string tag from graphql-tag with one or more s 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.

options.fragmentName (optional)
string

The name of the in your GraphQL document to be used. If you do not provide a fragmentName and there is only one in your fragment document then that will be used.

options.id (optional)
string

The 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.

options.overwrite (optional)
boolean

When true, ignore existing data rather than merging it with incoming data (default: false).

options.variables (optional)
TVariables

Any s that your GraphQL s depend on.

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.

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.

Parameters
Name / Type
Description
cb
() => Promise<any>

Remove all data from the store. Unlike resetStore, clearStore will not refetch any active queries.

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.

Parameters
Name / Type
Description
cb
() => Promise<any>

Call this method to terminate any active client processes, making it safe to dispose of this ApolloClient instance.

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.

Parameters
Name / Type
Description
includeStandby (optional)
boolean

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.

Parameters
Name / Type
Description
options
RefetchQueriesOptions<TCache, TResult>
Show/hide child attributes
options.include (optional)
RefetchQueriesInclude
options.onQueryUpdated (optional)
OnQueryUpdated<TResult> | null
options.optimistic (optional)
boolean
options.updateCache (optional)
(cache: TCache) => void

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.

Parameters
Name / Type
Description
include (optional)
RefetchQueriesInclude

Types

ApolloClientOptions

(src/core/ApolloClient.ts)
Properties
Name / Type
Description
cache
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.

link (optional)
ApolloLink

You 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.

uri (optional)
string | UriFunction

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.

connectToDevTools (optional)
boolean

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).

defaultOptions (optional)
DefaultOptions

Provide 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.

name (optional)
string

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.

version (optional)
string

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.

assumeImmutableResults (optional)
boolean

If true, Apollo Client will assume results read from the cache are never mutated by application code, which enables substantial performance optimizations.

credentials (optional)
string
documentTransform (optional)
DocumentTransform
fragmentMatcher (optional)
FragmentMatcher
headers (optional)
Record<string, string>
queryDeduplication (optional)
boolean

If false, Apollo Client sends every created query to the server, even if a completely identical query (identical in terms of query string, values, and Name) is already in flight.

resolvers (optional)
Resolvers | Resolvers[]
ssrForceFetchDelay (optional)
number

The time interval (in milliseconds) before Apollo Client force-fetches queries after a server-side render.

ssrMode (optional)
boolean

When using Apollo Client for server-side rendering, set this to true so that the getDataFromTree function can work effectively.

typeDefs (optional)
string | string[] | DocumentNode | DocumentNode[]
Properties
Name / Type
Description
mutate (optional)
Partial<MutationOptions<any, any, any>>
query (optional)
Partial<QueryOptions<any, any>>
watchQuery (optional)
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.

Previous
Hooks migration guide
Next
InMemoryCache
Edit on GitHubEditForumsDiscord