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

This watches the cache store of the according to the options specified and returns an ObservableQuery. We can subscribe to this ObservableQuery and receive updated results through a observer when the cache store changes.

Note that this method is not an implementation of . Rather, it uses Apollo's store in order to reactively deliver updates to your results.

For example, suppose you call watch on a 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

function watchQuery(
options: WatchQueryOptions<TVariables, T>
): ObservableQuery<T, TVariables>

Parameters

Name / Type
Description

options

WatchQueryOptions<TVariables, T>
Show/hide child attributes
Operation options

errorPolicy (optional)

ErrorPolicy

Specifies how the handles a response that returns both errors and partial results.

For details, see GraphQL error policies.

The default value is none, meaning that the result includes error details but not partial results.

DocumentNode | TypedDocumentNode<T, TVariables>

A string parsed into an AST with the gql template literal.

An object containing all of the your requires to execute.

Each key in the object corresponds to a name, and that key's value corresponds to the variable value.

Networking options
DefaultContext

If you're using Apollo Link, this object is the initial value of the context object that's passed along your link chain.

If true, the in-progress 's associated component re-renders whenever the network status changes or a network error occurs.

The default value is false.

Specifies the interval (in milliseconds) at which the polls for updated results.

The default value is 0 (no polling).

A callback function that's called whenever a refetch attempt occurs while polling. If the function returns true, the refetch is skipped and not reattempted until the next poll interval.

Caching options
WatchQueryFetchPolicy

Specifies how the interacts with the cache during execution (for example, whether it checks the cache for results before sending a request to the server).

For details, see Setting a fetch policy.

The default value is cache-first.

WatchQueryFetchPolicy

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

WatchQueryFetchPolicy | ((this: WatchQueryOptions<TVariables, T>, currentFetchPolicy: WatchQueryFetchPolicy, context: NextFetchPolicyContext<T, TVariables>) => WatchQueryFetchPolicy)

Specifies the FetchPolicy to be used after this has completed.

Specifies whether a 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 3.x.

If true, the can return partial results from the cache if the cache doesn't contain results for all queried .

The default value is false.

Other

⚠️ Deprecated

Using canonizeResults can result in memory leaks so we generally do not recommend using this option anymore. A future version of will contain a similar feature without the risk of memory leaks.

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

⚠️ Deprecated

Setting this option is unnecessary in 3, thanks to a more consistent application of fetch policies. It might be removed in a future release.

If true, causes a refetch if the query result is detected as partial.

The default value is false.

Result

ObservableQuery<T, TVariables>

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.

Signature

function query(
options: QueryOptions<TVariables, T>
): Promise<ApolloQueryResult<T>>

Parameters

Name / Type
Description

options

QueryOptions<TVariables, T>

An object of type QueryOptions that allows us to describe how this should be treated e.g. whether it should hit the server at all or just resolve from the cache, etc.

Show/hide child attributes
Operation options

Specifies how the handles a response that returns both errors and partial results.

For details, see GraphQL error policies.

The default value is none, meaning that the result includes error details but not partial results.

DocumentNode | TypedDocumentNode<T, TVariables>

A string parsed into an AST with the gql template literal.

An object containing all of the your requires to execute.

Each key in the object corresponds to a name, and that key's value corresponds to the variable value.

Networking options
DefaultContext

If you're using Apollo Link, this object is the initial value of the context object that's passed along your link chain.

If true, the in-progress 's associated component re-renders whenever the network status changes or a network error occurs.

The default value is false.

Specifies the interval (in milliseconds) at which the polls for updated results.

The default value is 0 (no polling).

Caching options

Specifies how the interacts with the cache during execution (for example, whether it checks the cache for results before sending a request to the server).

For details, see Setting a fetch policy.

The default value is cache-first.

If true, the can return partial results from the cache if the cache doesn't contain results for all queried .

The default value is false.

Other

⚠️ Deprecated

Using canonizeResults can result in memory leaks so we generally do not recommend using this option anymore. A future version of will contain a similar feature without the risk of memory leaks.

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

⚠️ Deprecated

Setting this option is unnecessary in 3, thanks to a more consistent application of fetch policies. It might be removed in a future release.

If true, causes a refetch if the query result is detected as partial.

The default value is false.

Result

Promise<ApolloQueryResult<T>>
Show/hide child attributes
Other
ApolloError

The single Error object that is passed to onError and use hooks, and is often thrown during manual client.query calls. This will contain both a NetworkError and any Errors. See https://www.apollographql.com/docs/react/data/error-handling/ for more information.

ReadonlyArray<GraphQLError>

A list of any errors that occurred during server-side execution of a . See https://www.apollographql.com/docs/react/data/error-handling/ for more information.

boolean
NetworkStatus

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

function mutate(
options: MutationOptions<TData, TVariables, TContext>
): Promise<FetchResult<TData>>

Parameters

Name / Type
Description

options

MutationOptions<TData, TVariables, TContext>
Show/hide child attributes
Operation options

If true, makes sure all queries included in refetchQueries are completed before the is considered complete.

The default value is false (queries are refetched asynchronously).

Specifies how the handles a response that returns both errors and partial results.

For details, see GraphQL error policies.

The default value is none, meaning that the result includes error details but not partial results.

DocumentNode | TypedDocumentNode<TData, TVariables>

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

OnQueryUpdated<any>

Optional callback for intercepting queries whose cache data has been updated by the , as well as any queries specified in the refetchQueries: [...] list passed to client.mutate.

Returning a Promise from onQueryUpdated will cause the final Promise to await the returned Promise. Returning false causes the to be ignored.

((result: FetchResult<TData>) => InternalRefetchQueriesInclude) | InternalRefetchQueriesInclude

An array (or a function that returns an array) that specifies which queries you want to refetch after the occurs.

Each array value can be either:

  • An object containing the query to execute, along with any variables

  • A string indicating the of the to refetch

An object containing all of the your requires to execute.

Each key in the object corresponds to a name, and that key's value corresponds to the variable value.

Networking options

If you're using Apollo Link, this object is the initial value of the context object that's passed along your link chain.

Caching options
MutationFetchPolicy

Provide no-cache if the 's result should not be written to the cache.

The default value is network-only (which means the result is written to the cache).

Unlike queries, do not support fetch policies besides network-only and no-cache.

TData | ((vars: TVariables, { IGNORE }: { IGNORE: IgnoreModifier; }) => TData)

By providing either an object or a callback function that, when invoked after a , allows you to return optimistic data and optionally skip updates via the IGNORE sentinel object, caches this temporary (and potentially incorrect) response until the completes, enabling more responsive UI updates.

For more information, see Optimistic mutation results.

MutationUpdaterFunction<TData, TVariables, TContext, TCache>

A function used to update the cache after the completes.

For more information, see Updating the cache after a mutation.

Other

To avoid retaining sensitive information from root , v3.4+ automatically clears any ROOT_MUTATION 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.

MutationQueryReducersMap<TData>

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

Result

Promise<FetchResult<TData>>

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

Signature

function subscribe(
options: SubscriptionOptions<TVariables, T>
): Observable<FetchResult<T>>

Parameters

Name / Type
Description

options

SubscriptionOptions<TVariables, T>
Show/hide child attributes
Other
DefaultContext

Shared context between your component and your network interface ().

Specifies the ErrorPolicy to be used for this

How you want your component to interact with the Apollo cache. For details, see Setting a fetch policy.

DocumentNode | TypedDocumentNode<T, TVariables>

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

An object containing all of the your needs to execute

Result

Observable<FetchResult<T>>

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

function readQuery(
options: DataProxy.Query<TVariables, T>,
optimistic?: boolean
): T | null

Parameters

Name / Type
Description

options

DataProxy.Query<TVariables, T>

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

Result

T | null

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

You must pass in a 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.

Signature

function readFragment(
options: DataProxy.Fragment<TVariables, T>,
optimistic?: boolean
): T | null

Parameters

Name / Type
Description

options

DataProxy.Fragment<TVariables, T>

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

Result

T | null

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

function writeQuery(
options: DataProxy.WriteQueryOptions<TData, TVariables>
): Reference | undefined

Parameters

Name / Type
Description

options

DataProxy.WriteQueryOptions<TData, TVariables>

Result

Reference | undefined
Show/hide child attributes
Other
string

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

You must pass in a 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.

Signature

function writeFragment(
options: DataProxy.WriteFragmentOptions<TData, TVariables>
): Reference | undefined

Parameters

Name / Type
Description

options

DataProxy.WriteFragmentOptions<TData, TVariables>

Result

Reference | undefined
Show/hide child attributes
Other
string

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

function resetStore(): Promise<ApolloQueryResult<any>[] | null>

Result

Promise<ApolloQueryResult<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

function onResetStore(
cb: () => Promise<any>
): () => void

Parameters

Name / Type
Description

cb

() => Promise<any>

Result

() => void

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

Signature

function clearStore(): 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

function onClearStore(
cb: () => Promise<any>
): () => void

Parameters

Name / Type
Description

cb

() => Promise<any>

Result

() => void

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

Signature

function stop(): 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.

Signature

function reFetchObservableQueries(
includeStandby?: boolean
): Promise<ApolloQueryResult<any>[]>

Parameters

Name / Type
Description

Result

Promise<ApolloQueryResult<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

function refetchQueries(
options: RefetchQueriesOptions<TCache, TResult>
): RefetchQueriesResult<TResult>

Parameters

Name / Type
Description

options

RefetchQueriesOptions<TCache, TResult>
Show/hide child attributes
Other
RefetchQueriesInclude
OnQueryUpdated<TResult> | null
(cache: TCache) => void

Result

RefetchQueriesResult<TResult>
Show/hide child attributes

(Warning: some properties might be missing from the table due to complex inheritance!)
Other
ObservableQuery<any>[]
InternalRefetchQueriesResult<TResult>[]

Get all currently active ObservableQuery objects, in a Map keyed by ID strings.

An "active" 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 names or Node objects.

Signature

function getObservableQueries(
include?: RefetchQueriesInclude
): Map<string, ObservableQuery<any>>

Parameters

Name / Type
Description

include (optional)

RefetchQueriesInclude

Result

Map<string, ObservableQuery<any>>

Types

Properties

Name / Type
Description
ApolloCache<TCacheShape>

The cache that should use to store results locally. The recommended cache is InMemoryCache, which is provided by the @apollo/client package.

For more information, see Configuring the cache.

ApolloLink

You can provide an ApolloLink instance to serve as '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

The URI of the endpoint that will communicate with.

One of uri or link is required. If you provide both, link takes precedence.

If true, the Apollo Client Devtools browser extension can connect to .

The default value is false in production and true in development (if there is a window object).

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.

A custom name (e.g., iOS) that identifies this particular client among your set of clients. and Apollo Studio use this property as part of the client awareness feature.

A custom version that identifies the current version of this particular client (e.g., 1.2). and Apollo Studio use this property as part of the client awareness feature.

This is not the version of that you are using, but rather any version string that helps you differentiate between versions of your client.

Other

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

Partial<DefaultContext>
Record<string, string>

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.

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

Resolvers | Resolvers[]

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

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

string | string[] | DocumentNode | DocumentNode[]

Properties

Name / Type
Description
Other
Partial<MutationOptions<any, any, any>>
Partial<QueryOptions<any, any>>
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 '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

© 2024 Apollo Graph Inc.

Privacy Policy

Company