Join us from October 8-10 in New York City to learn the latest tips, trends, and news about GraphQL Federation and API platform engineering.Join us for GraphQL Summit 2024 in NYC
Docs
Start for Free
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): ApolloClient<TCacheShape>

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

Constructs an instance of ApolloClient.

Options
Name /
Type
Description
assumeImmutableResults
boolean
cache
ApolloCache<TCacheShape>
connectToDevTools
boolean
credentials
string
defaultContext
Partial<DefaultContext>
defaultOptions
DefaultOptions
documentTransform
DocumentTransform
fragmentMatcher
FragmentMatcher
headers
Record<string, string>
link
ApolloLink
name
string
queryDeduplication
boolean
resolvers
any
ssrForceFetchDelay
number
ssrMode
boolean
typeDefs
any
uri
string | UriFunction
version
string

The constructor for ApolloClient accepts an ApolloClientOptions object that supports the required and optional 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 '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 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.

Options
Name /
Type
Description
canonizeResults
boolean
context
DefaultContext
errorPolicy
ErrorPolicy
fetchPolicy
WatchQueryFetchPolicy
initialFetchPolicy
WatchQueryFetchPolicy
nextFetchPolicy
any
notifyOnNetworkStatusChange
boolean
partialRefetch
boolean
pollInterval
number
query
DocumentNode | TypedDocumentNode
refetchWritePolicy
RefetchWritePolicy
returnPartialData
boolean
skipPollAttempt
boolean
variables
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.

Options
Name /
Type
Description
canonizeResults
boolean
context
DefaultContext
errorPolicy
ErrorPolicy
fetchPolicy
FetchPolicy
notifyOnNetworkStatusChange
boolean
partialRefetch
boolean
pollInterval
number
query
DocumentNode | TypedDocumentNode
returnPartialData
boolean
variables
TVariables

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:

Options
Name /
Type
Description
awaitRefetchQueries
boolean
context
TContext
errorPolicy
ErrorPolicy
fetchPolicy
MutationFetchPolicy
keepRootFields
boolean
mutation
DocumentNode | TypedDocumentNode
onQueryUpdated
OnQueryUpdated<any>
optimisticResponse
any
refetchQueries
any
update
MutationUpdaterFunction<TData, TVariables, TContext, TCache>
updateQueries
MutationQueryReducersMap<TData>
variables
TVariables

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
errorPolicy
ErrorPolicy
fetchPolicy
FetchPolicy
query
DocumentNode | TypedDocumentNode
variables
TVariables

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
boolean

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
boolean
Options
Name /
Type
Description
fragment
DocumentNode | TypedDocumentNode
fragmentName
string
id
string
variables
TVariables

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
boolean
data
TData
id
string
overwrite
boolean
query
DocumentNode | TypedDocumentNode
variables
TVariables

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
boolean
data
TData
fragment
DocumentNode | TypedDocumentNode
fragmentName
string
id
string
overwrite
boolean
variables
TVariables

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

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

Arguments
Name /
Type
Description
includeStandby
boolean

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
boolean

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>

Update the variables of this observable query, and fetch the new results if they've changed. Most users should prefer refetch instead of setVariables in order to to be properly notified of results even when they come from the cache.

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

A function that helps you fetch the next set of results for a paginated list field.

Arguments
Name /
Type
Description
fetchMoreOptions
any

A function that enables you to update the query's cached result without executing a followup GraphQL operation.

See using updateQuery and updateFragment for additional information.

Arguments
Name /
Type
Description
mapFn
TData

A function that instructs the query to begin re-executing at a specified interval (in milliseconds).

Arguments
Name /
Type
Description
pollInterval
number

A function that instructs the query to stop polling after a previous call to startPolling.

A function that enables you to execute a subscription, 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.

Types

Properties
Name /
Type
Description
assumeImmutableResults
boolean
cache
ApolloCache<TCacheShape>
connectToDevTools
boolean
credentials
string
defaultContext
Partial<DefaultContext>
defaultOptions
DefaultOptions
documentTransform
DocumentTransform
fragmentMatcher
FragmentMatcher
headers
Record<string, string>
link
ApolloLink
name
string
queryDeduplication
boolean
resolvers
any
ssrForceFetchDelay
number
ssrMode
boolean
typeDefs
any
uri
string | UriFunction
version
string
Properties
Name /
Type
Description
mutate
Partial<MutationOptions>
query
Partial<QueryOptions>
react
any
watchQuery
Partial<WatchQueryOptions>

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

Enumeration Members
Name /
Type
Description
error
any
fetchMore
any
loading
any
poll
any
ready
any
refetch
any
setVariables
any
Properties
Name /
Type
Description
data
T
error
ApolloError
errors
any
loading
boolean
networkStatus
NetworkStatus
partial
boolean
Previous
Authentication
Next
@apollo/react-hooks
Rate articleRateEdit on GitHubEditForumsDiscord

© 2024 Apollo Graph Inc., d/b/a Apollo GraphQL.

Privacy Policy

Company