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 cache.identify
. 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<TData, TVariables>( 2 options: ApolloClient.WatchQueryOptions<TData, TVariables> 3): ObservableQuery<TData, TVariables>
Parameters
Result
ObservableQuery<TData, 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<TData, TVariables>( 2 options: ApolloClient.QueryOptions<TData, TVariables> 3): Promise<ApolloClient.QueryResult<MaybeMasked<TData>>>
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<ApolloClient.QueryResult<MaybeMasked<TData>>>
Show/hide child attributes
MaybeMasked<TData> | undefined
An object containing the result of your GraphQL query after it completes.
This value might be undefined
if a query results in one or more errors (depending on the query's errorPolicy
).
ErrorLike
A single ErrorLike object describing the error that occured during the latest query execution.
For more information, see Handling operation errors.
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, TCache>( 2 options: ApolloClient.MutateOptions<TData, TVariables, TCache> 3): Promise<ApolloClient.MutateResult<MaybeMasked<TData>>>
Parameters
Result
Promise<ApolloClient.MutateResult<MaybeMasked<TData>>>
Show/hide child attributes
MaybeMasked<TData> | undefined
The data returned from your mutation. Can be undefined
if the errorPolicy
is all
or ignore
and the server returns a GraphQL response with errors
but not data
or a network error is returned.
ErrorLike
If the mutation produces one or more errors, this object contains either an array of graphQLErrors
or a single networkError
. Otherwise, this value is undefined
.
For more information, see Handling operation errors.
Record<string, unknown>
Custom extensions returned from the GraphQL server
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<TData, TVariables>( 2 options: ApolloClient.SubscribeOptions<TData, TVariables> 3): SubscriptionObservable<ApolloClient.SubscribeResult<MaybeMasked<TData>>>
Parameters
Result
SubscriptionObservable<ApolloClient.SubscribeResult<MaybeMasked<TData>>>
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 cache.identify
use readFragment
.
Signature
1readQuery<TData, TVariables>( 2 options: ApolloClient.ReadQueryOptions<TData, TVariables> 3): Unmasked<TData> | null
Parameters
Result
Unmasked<TData> | 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
1readFragment<TData, TVariables>( 2 options: ApolloClient.ReadFragmentOptions<TData, TVariables> 3): Unmasked<TData> | null
Parameters
Result
Unmasked<TData> | 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 cache.identify
then use writeFragment
.
Signature
1writeQuery<TData, TVariables>( 2 options: ApolloClient.WriteQueryOptions<TData, TVariables> 3): Reference | undefined
Parameters
Result
Reference | undefined
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
1writeFragment<TData, TVariables>( 2 options: ApolloClient.WriteFragmentOptions<TData, TVariables> 3): Reference | undefined
Parameters
Result
Reference | undefined
watchFragment
Requires ≥ 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<TData, TVariables>( 2 options: ApolloClient.WatchFragmentOptions<TData, TVariables> 3): Observable<ApolloClient.WatchFragmentResult<MaybeMasked<TData>>>
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<ApolloClient.WatchFragmentResult<MaybeMasked<TData>>>
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<ApolloClient.QueryResult<any>[] | null>
Result
Promise<ApolloClient.QueryResult<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): () => void
Parameters
Result
() => void
Remove 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): () => void
Parameters
Result
() => void
Call this method to terminate any active client processes, making it safe to dispose of this ApolloClient
instance.
This method performs aggressive cleanup to prevent memory leaks:
Unsubscribes all active
ObservableQuery
instances by emitting acompleted
eventRejects all currently running queries with "QueryManager stopped while query was in flight"
Removes all queryRefs from the suspense cache
Signature
1stop(): 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.
Note: cache-only
queries are not refetched by this function.
Signature
1refetchObservableQueries( 2 includeStandby?: boolean 3): Promise<ApolloClient.QueryResult<any>[]>
Parameters
Result
Promise<ApolloClient.QueryResult<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: ApolloClient.RefetchQueriesOptions<TCache, TResult> 3): ApolloClient.RefetchQueriesResult<TResult>
Parameters
Show/hide child attributes
RefetchQueriesInclude
Optional array specifying queries to refetch. Each element can be either a query's string name or a DocumentNode
object.
Pass "active"
as a shorthand to refetch all active queries, or "all"
to refetch all active and inactive queries.
Analogous to the options.refetchQueries
array for mutations.
OnQueryUpdated<TResult> | null
Optional callback function that's called once for each ObservableQuery
that's either affected by options.updateCache
or listed in options.include
(or both).
If onQueryUpdated
is not provided, the default implementation returns the result of calling observableQuery.refetch()
. When onQueryUpdated
is provided, it can dynamically decide whether (and how) each query should be refetched.
Returning false
from onQueryUpdated
prevents the associated query from being refetched.
boolean
If true
, the options.updateCache
function is executed on a temporary optimistic layer of InMemoryCache
, so its modifications can be discarded from the cache after observing which fields it invalidated.
Defaults to false
, meaning options.updateCache
updates the cache in a lasting way.
(cache: TCache) => void
Optional function that updates cached fields to trigger refetches of queries that include those fields.
Result
ApolloClient.RefetchQueriesResult<TResult>
Show/hide child attributes
(Warning: some properties might be missing from the table due to complex inheritance!)
ObservableQuery<any>[]
An array of ObservableQuery objects corresponding 1:1 to TResult values in the results arrays (both the result
property and the resolved value).
InternalRefetchQueriesResult<TResult>[]
An array of results that were either returned by onQueryUpdated
, or provided by default in the absence of onQueryUpdated
, including pending promises.
If onQueryUpdated
returns false
for a given query, no result is provided for that query.
If onQueryUpdated
returns true
, the resulting Promise<ApolloQueryResult<any>>
is included in the results
array instead of true
.
Get all currently active ObservableQuery
objects, in a Set
.
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.
Note: This method only returns queries that have active subscribers. Queries without subscribers are not tracked by the client.
Signature
1getObservableQueries( 2 include?: RefetchQueriesInclude 3): Set<ObservableQuery<any>>
Parameters
Result
Set<ObservableQuery<any>>
Exposes the cache's complete state, in a serializable format for later restoration.
This can be useful for debugging in order to inspect the full state of the cache.
Signature
1extract( 2 optimistic?: boolean 3): unknown
Parameters
Determines whether the result contains data from the optimistic layer
Result
unknown
Replaces existing state in the cache (if any) with the values expressed by serializedState
.
Called when hydrating a cache (server side rendering, or offline storage), and also (potentially) during hot reloads.
Signature
1restore( 2 serializedState: unknown 3): ApolloCache
Parameters
Result
ApolloCache
Define a new ApolloLink (or link chain) that Apollo Client will use.
Signature
1setLink( 2 newLink: ApolloLink 3): void
Parameters
Types
ApolloCache
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.
ApolloLink
An ApolloLink
instance to serve as Apollo Client's network layer. For more information, see Advanced HTTP networking.
ApolloClient.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.
If true
, Apollo Client will assume results read from the cache are never mutated by application code, which enables substantial performance optimizations.
ClientAwarenessLink.ClientAwarenessOptions
boolean
Determines if data masking is enabled for the client.
Partial<DefaultContext>
devtools
(optional)Requires ≥ 3.11.0
ApolloClient.DevtoolsOptions
Configuration used by the Apollo Client Devtools extension for this client.
DocumentTransform
ClientAwarenessLink.EnhancedClientAwarenessOptions
Incremental.Handler<any>
Determines the strategy used to parse incremental chunks from @defer
queries.
LocalState
boolean
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.
The time interval (in milliseconds) before Apollo Client force-fetches queries after a server-side render.
boolean
When using Apollo Client for server-side rendering, set this to true
so that the getDataFromTree
function can work effectively.
Partial<ApolloClient.MutateOptions<any, any, any>>
Partial<ApolloClient.QueryOptions<any, any>>
Partial<ApolloClient.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
useQuery
hook uses Apollo Client'swatchQuery
function. To setdefaultOptions
when using theuseQuery
hook, make sure to set them under thedefaultOptions.watchQuery
property.
boolean
If true
, the Apollo Client Devtools browser extension can connect to this ApolloClient
instance.
The default value is false
in production and true
in development if there is a window
object.
string
Optional name for this ApolloClient
instance in the devtools. This is useful when you instantiate multiple clients and want to be able to identify them by name.