Join us for GraphQL Summit, October 10-12 in San Diego. Super Early Bird registration ends soon!
Docs
Try Apollo Studio
You're viewing documentation for a previous version of this software. Switch to the latest stable version.

class ApolloClient


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

constructor(options)

(src/core/ApolloClient.ts, line 127)

Constructs an instance of ApolloClient.

The constructor for ApolloClient accepts an ApolloClientOptions object that supports the required and optional fields listed below. These fields make it easy to customize how Apollo works based on your application's needs.

Example constructor call

import { ApolloClient } from 'apollo-client';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { HttpLink } from 'apollo-link-http';
// Instantiate required constructor fields
const cache = new InMemoryCache();
const link = new HttpLink({
uri: 'http://localhost:4000/',
});
const client = new ApolloClient({
// Provide required constructor fields
cache: cache,
link: link,
// Provide some optional constructor fields
name: 'react-web-client',
version: '1.3',
queryDeduplication: false,
defaultOptions: {
watchQuery: {
fetchPolicy: 'cache-and-network',
},
},
});

Required fields

NameDescription
linkApollo Client uses an Apollo Link instance to serve as its network layer. The vast majority of clients use HTTP and should provide an instance of HttpLink from the apollo-link-http package.

For more information, see the Apollo Link documentation.
cacheApollo Client uses an Apollo Cache instance to handle its caching strategy. The recommended cache is apollo-cache-inmemory, which exports an { InMemoryCache }. For more information, see Configuring the cache.

Optional fields

NameDescription
nameA custom name (e.g., iOS) that identifies this particular client among your set of clients. Apollo Server uses this property as part of its Client Awareness feature.
versionA custom version that identifies the current version of this particular client (e.g., 1.2). Apollo Server uses this property as part of its Client Awareness feature.

Note that this version string 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.
ssrModeWhen using Apollo Client for server-side rendering, set this to true so that React Apollo's getDataFromTree function can work effectively.
ssrForceFetchDelayProvide this to specify a time interval (in milliseconds) before Apollo Client force-fetches queries after a server-side render. This value is 0 by default.
connectToDevToolsSet this to true to allow the Apollo Client Devtools Chrome extension to connect to your application's Apollo Client in production. (This connection is allowed automatically in dev mode.)
queryDeduplicationSet this to false to force all created queries to be sent to the server, even if a query with completely identical parameters (query, variables, operationName) is already in flight.
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.

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 <Query /> React component uses Apollo Client's watchQuery function. To set defaultOptions when using the <Query /> component, make sure to set them under the defaultOptions.watchQuery property.

ApolloClient 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 a GraphQL 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.

Options
Name /
Type
Description
canonizeResults
any

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

context
DefaultContext

Context to be passed to link execution chain

errorPolicy
any

Specifies the ErrorPolicy to be used for this query

fetchPolicy
any

Specifies the FetchPolicy to be used for this query.

initialFetchPolicy
any

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

nextFetchPolicy
any

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

notifyOnNetworkStatusChange
any

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

partialRefetch
any

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

pollInterval
any

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

query
DocumentNode | TypedDocumentNode

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

refetchWritePolicy
RefetchWritePolicy

Specifies whether a {@link 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.

returnPartialData
any

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

variables
TVariables

A map going from variable 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.

Options
Name /
Type
Description
canonizeResults
any

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

context
DefaultContext

Context to be passed to link execution chain

errorPolicy
any

Specifies the ErrorPolicy to be used for this query

fetchPolicy
any

Specifies the FetchPolicy to be used for this query

notifyOnNetworkStatusChange
any

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

partialRefetch
any

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

pollInterval
any

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

query
DocumentNode | TypedDocumentNode

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

returnPartialData
any

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

variables
TVariables

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

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.

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

Options
Name /
Type
Description
awaitRefetchQueries
any

By default, refetchQueries does not wait for the refetched queries to be completed, before resolving the mutation Promise. This ensures that query refetching does not hold up mutation 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 mutation can be marked as resolved.

context
TContext

The context to be passed to the link execution chain. This context will only be used with this mutation. 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.

errorPolicy
any

Specifies the ErrorPolicy to be used for this operation

fetchPolicy
MutationFetchPolicy

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

keepRootFields
any

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.

mutation
DocumentNode | TypedDocumentNode

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

onQueryUpdated
(ObservableQuery<>, Cache.DiffResult<>, any) => any<>

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

optimisticResponse
any

An object that represents the result of this mutation 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.

refetchQueries
any

A list of query names which will be refetched once this mutation 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.

update
(TCache, Omit<SingleExecutionResult | ExecutionPatchInitialResult | ExecutionPatchIncrementalResult, >, any) => any<TData, TVariables, TContext, TCache>

This function will be called twice over the lifecycle of a mutation. 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 mutation has successfully resolved. At that point update will be called with the actual mutation 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 mutation has completed, and you don't need to update the store, use the Promise returned from client.mutate instead.

updateQueries
[queryName:undefined]:(Record<, >, any) => Record<, ><T><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.

variables
TVariables

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

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

Options
Name /
Type
Description
context
DefaultContext

Context object to be passed through the link execution chain.

errorPolicy
any

Specifies the ErrorPolicy to be used for this operation

fetchPolicy
any

Specifies the FetchPolicy to be used for this subscription.

query
DocumentNode | TypedDocumentNode

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

variables
TVariables

An object that maps from the name of a variable as used in the subscription 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.

Arguments
Name /
Type
Description
optimistic
any

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

Arguments
Name /
Type
Description
optimistic
any

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

Options
Name /
Type
Description
fragment
DocumentNode | TypedDocumentNode

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.

fragmentName
any

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 your fragment document then that fragment will be used.

id
any

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.

variables
TVariables

Any variables that your GraphQL fragments depend on.

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.

Options
Name /
Type
Description
broadcast
any

Whether to notify query watchers (default: true).

data
TData

The data you will be writing to the store.

id
any

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.

overwrite
any

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

query
DocumentNode | TypedDocumentNode

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.

variables
TVariables

Any variables that the GraphQL query may depend on.

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.

Options
Name /
Type
Description
broadcast
any

Whether to notify query watchers (default: true).

data
TData

The data you will be writing to the store.

fragment
DocumentNode | TypedDocumentNode

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.

fragmentName
any

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 your fragment document then that fragment will be used.

id
any

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.

overwrite
any

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

variables
TVariables

Any variables that your GraphQL fragments 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.

Arguments
Name /
Type
Description
cb
() => Promise<>

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.

Arguments
Name /
Type
Description
cb
() => Promise<>

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.

Arguments
Name /
Type
Description
includeStandby
any

ObservableQuery functions

ApolloClient Observables extend the Observables implementation provided by zen-observable. Refer to the zen-observable documentation for additional context and API options.

Arguments
Name /
Type
Description
saveAsLastResult
any

Update the variables of this observable query, and fetch the new results. This method should be preferred over setVariables in most use cases.

Arguments
Name /
Type
Description
variables
Partial<TVariables>
Arguments
Name /
Type
Description
newOptions
Partial<WatchQueryOptions>

This is for internal use only. Most users should instead use refetch in order to be properly notified of results even when they come from cache.

Update the variables of this observable query, and fetch the new results if they've changed. If you want to force new results, use refetch.

Note: the next callback will not fire if the variables have not changed or if the result is coming from cache.

Note: the promise will return the old results immediately if the variables have not changed.

Note: the promise will return null immediately if the query is not active (there are no subscribers).

Arguments
Name /
Type
Description
variables
TVariables
Arguments
Name /
Type
Description
fetchMoreOptions
any
Arguments
Name /
Type
Description
mapFn
(TData, Pick<WatchQueryOptions, >) => TData
Arguments
Name /
Type
Description
pollInterval
any

Types

Properties
Name /
Type
Description
assumeImmutableResults
any
cache
ApolloCache<TCacheShape>
connectToDevTools
any
credentials
any
defaultOptions
DefaultOptions
fragmentMatcher
(any, any, any) => any
headers
Record<, >
link
ApolloLink
name
any
queryDeduplication
any
resolvers
any
ssrForceFetchDelay
any
ssrMode
any
typeDefs
any
uri
any
version
any
Properties
Name /
Type
Description
mutate
Partial<MutationOptions>
query
Partial<QueryOptions>
watchQuery
Partial<WatchQueryOptions>

The current status of a query’s execution in our system.

Properties
Name /
Type
Description
data
T
error
ApolloError

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

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

loading
any
networkStatus
NetworkStatus
partial
any
Edit on GitHub
Previous
Authentication
Next
@apollo/react-hooks