@apollo/client
- Version 3.13.8
- Published
- 7.44 MB
- 13 dependencies
- MIT license
Install
npm i @apollo/client
yarn add @apollo/client
pnpm add @apollo/client
Overview
A fully-featured caching GraphQL client.
Index
Variables
Functions
- checkFetcher()
- createHttpLink()
- createQueryPreloader()
- createSignalIfSupported()
- defaultDataIdFromObject()
- fromError()
- fromPromise()
- getApolloContext()
- isApolloError()
- isNetworkRequestSettled()
- isReference()
- makeReference()
- makeVar()
- mergeOptions()
- operationName()
- parseAndCheckHttpResponse()
- parser()
- rewriteURIForGET()
- selectHttpOptionsAndBody()
- selectHttpOptionsAndBodyInternal()
- selectURI()
- serializeFetchParameter()
- throwServerError()
- toPromise()
- useApolloClient()
- useBackgroundQuery()
- useFragment()
- useLazyQuery()
- useLoadableQuery()
- useMutation()
- useQuery()
- useQueryRefHandlers()
- useReactiveVar()
- useReadQuery()
- useSubscription()
- useSuspenseFragment()
- useSuspenseQuery()
Classes
ApolloCache
- assumeImmutableResults
- batch()
- diff()
- evict()
- extract()
- fragmentMatches()
- gc()
- identify()
- lookupFragment()
- modify()
- performTransaction()
- read()
- readFragment()
- readQuery()
- recordOptimisticTransaction()
- removeOptimistic()
- reset()
- restore()
- transformDocument()
- transformForLink()
- updateFragment()
- updateQuery()
- watch()
- watchFragment()
- write()
- writeFragment()
- writeQuery()
ApolloClient
- addResolvers()
- cache
- clearStore()
- defaultContext
- defaultOptions
- devtoolsConfig
- disableNetworkFetches
- documentTransform
- extract()
- getMemoryInternals
- getObservableQueries()
- getResolvers()
- link
- mutate()
- onClearStore()
- onResetStore()
- query()
- queryDeduplication
- readFragment()
- readQuery()
- reFetchObservableQueries()
- refetchQueries()
- resetStore()
- restore()
- setLink()
- setLocalStateFragmentMatcher()
- setResolvers()
- stop()
- subscribe()
- typeDefs
- version
- watchFragment()
- watchQuery()
- writeFragment()
- writeQuery()
ObservableQuery
- fetchMore()
- getCurrentResult()
- getLastError()
- getLastResult()
- hasObservers()
- isDifferentFromLastResult()
- options
- query
- queryId
- queryName
- refetch()
- reobserve()
- reobserveAsConcast()
- resetLastResults()
- resetQueryStoreErrors()
- resubscribeAfterError()
- result()
- setOptions()
- setVariables()
- silentSetOptions()
- startPolling()
- stopPolling()
- subscribeToMore()
- updateQuery()
- variables
Interfaces
Enums
Type Aliases
- ApolloReducerConfig
- BackgroundQueryHookFetchPolicy
- ClientParseError
- CommonOptions
- DiffQueryAgainstStoreOptions
- DocumentTransformCacheKey
- ErrorPolicy
- ExecutionPatchResult
- FetchPolicy
- FetchResult
- FieldMergeFunction
- FieldPolicy
- FieldReadFunction
- FragmentMatcher
- FragmentType
- IdGetter
- InternalRefetchQueriesInclude
- InternalRefetchQueriesMap
- InternalRefetchQueriesResult
- InternalRefetchQueryDescriptor
- LazyQueryExecFunction
- LazyQueryResult
- LazyQueryResultTuple
- LoadableQueryHookFetchPolicy
- LoadQueryFunction
- Masked
- MaskedDocumentNode
- MaybeMasked
- MethodKeys
- MutationFetchPolicy
- MutationFunction
- MutationQueryReducer
- MutationQueryReducersMap
- MutationTuple
- MutationUpdaterFn
- MutationUpdaterFunction
- NextLink
- NoInfer
- OnQueryUpdated
- OperationVariables
- OptimisticStoreItem
- Path
- PossibleTypesMap
- PreloadQueryFetchPolicy
- PreloadQueryOptions
- QueryTuple
- ReadQueryOptions
- RefetchQueriesFunction
- RefetchQueriesInclude
- RefetchQueriesPromiseResults
- RefetchQueryDescriptor
- RefetchWritePolicy
- RequestHandler
- Resolver
- ServerError
- ServerParseError
- SkipToken
- StoreValue
- SubscribeToMoreUpdateQueryFn
- SuspenseQueryHookFetchPolicy
- Transaction
- TypePolicies
- TypePolicy
- Unmasked
- UpdateQueryOptions
- UseBackgroundQueryResult
- UseFragmentResult
- UseLoadableQueryResult
- UseSuspenseFragmentOptions
- UseSuspenseFragmentResult
- VariablesOption
- WatchFragmentResult
- WatchQueryFetchPolicy
Namespaces
Variables
variable ApolloConsumer
const ApolloConsumer: ReactTypes.FC<ApolloConsumerProps>;
variable ApolloProvider
const ApolloProvider: ReactTypes.FC<ApolloProviderProps<any>>;
variable concat
const concat: ( first: ApolloLink | RequestHandler, second: ApolloLink | RequestHandler) => ApolloLink;
variable defaultPrinter
const defaultPrinter: Printer;
variable empty
const empty: () => ApolloLink;
variable execute
const execute: ( link: ApolloLink, operation: GraphQLRequest<Record<string, any>>) => Observable< FetchResult<Record<string, any>, Record<string, any>, Record<string, any>>>;
variable fallbackHttpConfig
const fallbackHttpConfig: { http: HttpQueryOptions; headers: { accept: string; 'content-type': string }; options: { method: string };};
variable from
const from: (links: (ApolloLink | RequestHandler)[]) => ApolloLink;
variable resetApolloContext
const resetApolloContext: () => ReactTypes.Context<ApolloContextValue>;
Deprecated
This function has no "resetting" effect since Apollo Client 3.4.12, and will be removed in the next major version of Apollo Client. If you want to get the Apollo Context, use
getApolloContext
instead.
variable skipToken
const skipToken: Symbol;
variable split
const split: ( test: (op: Operation) => boolean, left: ApolloLink | RequestHandler, right?: ApolloLink | RequestHandler) => ApolloLink;
Functions
function checkFetcher
checkFetcher: (fetcher: typeof fetch | undefined) => void;
function createHttpLink
createHttpLink: (linkOptions?: HttpOptions) => ApolloLink;
function createQueryPreloader
createQueryPreloader: (client: ApolloClient<any>) => PreloadQueryFunction;
A higher order function that returns a
preloadQuery
function which can be used to begin loading a query with the givenclient
. This is useful when you want to start loading a query as early as possible outside of a React component.> Refer to the [Suspense - Initiating queries outside React](https://www.apollographql.com/docs/react/data/suspense#initiating-queries-outside-react) section for a more in-depth overview.
Parameter client
The
ApolloClient
instance that will be used to load queries from the returnedpreloadQuery
function.Returns
The
preloadQuery
function.Example 1
const preloadQuery = createQueryPreloader(client);3.9.0
function createSignalIfSupported
createSignalIfSupported: () => | { controller: boolean; signal: boolean } | { controller: AbortController; signal: AbortSignal };
Deprecated
This is not used internally any more and will be removed in the next major version of Apollo Client.
function defaultDataIdFromObject
defaultDataIdFromObject: ( { __typename, id, _id }: Readonly<StoreObject>, context?: KeyFieldsContext) => string | undefined;
function fromError
fromError: <T>(errorValue: any) => Observable<T>;
function fromPromise
fromPromise: <T>(promise: Promise<T>) => Observable<T>;
function getApolloContext
getApolloContext: () => ReactTypes.Context<ApolloContextValue>;
function isApolloError
isApolloError: (err: Error) => err is ApolloError;
function isNetworkRequestSettled
isNetworkRequestSettled: (networkStatus?: NetworkStatus) => boolean;
Returns true if the network request is in ready or error state according to a given network status.
function isReference
isReference: (obj: any) => obj is Reference;
function makeReference
makeReference: (id: string) => Reference;
function makeVar
makeVar: <T>(value: T) => ReactiveVar<T>;
function mergeOptions
mergeOptions: < TDefaultOptions extends Partial<OptionsUnion<any, any, any>>, TOptions extends TDefaultOptions>( defaults: TDefaultOptions | Partial<TDefaultOptions> | undefined, options: TOptions | Partial<TOptions>) => TOptions & TDefaultOptions;
function operationName
operationName: (type: DocumentType) => string;
function parseAndCheckHttpResponse
parseAndCheckHttpResponse: ( operations: Operation | Operation[]) => (response: Response) => Promise<any>;
function parser
parser: typeof parser;
function rewriteURIForGET
rewriteURIForGET: ( chosenURI: string, body: Body) => | { parseError: unknown; newURI?: undefined } | { newURI: string; parseError?: undefined };
function selectHttpOptionsAndBody
selectHttpOptionsAndBody: ( operation: Operation, fallbackConfig: HttpConfig, ...configs: Array<HttpConfig>) => { options: HttpConfig & Record<string, any>; body: Body };
function selectHttpOptionsAndBodyInternal
selectHttpOptionsAndBodyInternal: ( operation: Operation, printer: Printer, ...configs: HttpConfig[]) => { options: HttpConfig & Record<string, any>; body: Body };
function selectURI
selectURI: ( operation: Operation, fallbackURI?: string | ((operation: Operation) => string)) => any;
function serializeFetchParameter
serializeFetchParameter: (p: any, label: string) => string;
function throwServerError
throwServerError: (response: Response, result: any, message: string) => never;
function toPromise
toPromise: <R>(observable: Observable<R>) => Promise<R>;
function useApolloClient
useApolloClient: (override?: ApolloClient<object>) => ApolloClient<object>;
Returns
The
ApolloClient
instance being used by the application.Example 1
import { useApolloClient } from '@apollo/client';function SomeComponent() {const client = useApolloClient();// `client` is now set to the `ApolloClient` instance being used by the// application (that was configured using something like `ApolloProvider`)}3.0.0
function useBackgroundQuery
useBackgroundQuery: { < TData, TVariables extends OperationVariables, TOptions extends Omit< BackgroundQueryHookOptions<TData, OperationVariables>, 'variables' > >( query: DocumentNode | TypedDocumentNode<TData, TVariables>, options?: BackgroundQueryHookOptionsNoInfer<TData, TVariables> & TOptions ): [ ( | QueryRef< TOptions['errorPolicy'] extends 'ignore' | 'all' ? TOptions['returnPartialData'] extends true ? DeepPartial<TData> | undefined : TData | undefined : TOptions['returnPartialData'] extends true ? DeepPartial<TData> : TData, TVariables > | (TOptions['skip'] extends boolean ? undefined : never) ), UseBackgroundQueryResult<TData, TVariables> ]; <TData = unknown, TVariables extends OperationVariables = OperationVariables>( query: any, options: BackgroundQueryHookOptionsNoInfer<TData, TVariables> & { returnPartialData: true; errorPolicy: 'all' | 'ignore'; } ): [ QueryRef<DeepPartial<TData>, TVariables>, UseBackgroundQueryResult<TData, TVariables> ]; <TData = unknown, TVariables extends OperationVariables = OperationVariables>( query: any, options: BackgroundQueryHookOptionsNoInfer<TData, TVariables> & { errorPolicy: 'all' | 'ignore'; } ): [QueryRef<TData, TVariables>, UseBackgroundQueryResult<TData, TVariables>]; <TData = unknown, TVariables extends OperationVariables = OperationVariables>( query: any, options: BackgroundQueryHookOptionsNoInfer<TData, TVariables> & { skip: boolean; returnPartialData: true; } ): [ QueryRef<DeepPartial<TData>, TVariables>, UseBackgroundQueryResult<TData, TVariables> ]; <TData = unknown, TVariables extends OperationVariables = OperationVariables>( query: any, options: BackgroundQueryHookOptionsNoInfer<TData, TVariables> & { returnPartialData: true; } ): [ QueryRef<DeepPartial<TData>, TVariables>, UseBackgroundQueryResult<TData, TVariables> ]; <TData = unknown, TVariables extends OperationVariables = OperationVariables>( query: any, options: BackgroundQueryHookOptionsNoInfer<TData, TVariables> & { skip: boolean; } ): [QueryRef<TData, TVariables>, UseBackgroundQueryResult<TData, TVariables>]; <TData = unknown, TVariables extends OperationVariables = OperationVariables>( query: any, options?: BackgroundQueryHookOptionsNoInfer<TData, TVariables> ): [QueryRef<TData, TVariables>, UseBackgroundQueryResult<TData, TVariables>]; <TData = unknown, TVariables extends OperationVariables = OperationVariables>( query: any, options: typeof skipToken ): [undefined, UseBackgroundQueryResult<TData, TVariables>]; <TData = unknown, TVariables extends OperationVariables = OperationVariables>( query: any, options: | typeof skipToken | (BackgroundQueryHookOptionsNoInfer<TData, TVariables> & { returnPartialData: true; }) ): [ QueryRef<DeepPartial<TData>, TVariables>, UseBackgroundQueryResult<TData, TVariables> ]; <TData = unknown, TVariables extends OperationVariables = OperationVariables>( query: any, options?: | typeof skipToken | BackgroundQueryHookOptionsNoInfer<TData, TVariables> ): [QueryRef<TData, TVariables>, UseBackgroundQueryResult<TData, TVariables>];};
function useFragment
useFragment: <TData = any, TVars = OperationVariables>( options: UseFragmentOptions<TData, TVars>) => UseFragmentResult<TData>;
function useLazyQuery
useLazyQuery: < TData = any, TVariables extends OperationVariables = OperationVariables>( query: DocumentNode | TypedDocumentNode<TData, TVariables>, options?: LazyQueryHookOptions<NoInfer<TData>, NoInfer<TVariables>>) => LazyQueryResultTuple<TData, TVariables>;
A hook for imperatively executing queries in an Apollo application, e.g. in response to user interaction.
> Refer to the [Queries - Manual execution with useLazyQuery](https://www.apollographql.com/docs/react/data/queries#manual-execution-with-uselazyquery) section for a more in-depth overview of
useLazyQuery
.Parameter query
A GraphQL query document parsed into an AST by
gql
.Parameter options
Default options to control how the query is executed.
Returns
A tuple in the form of
[execute, result]
Example 1
import { gql, useLazyQuery } from "@apollo/client";const GET_GREETING = gql`query GetGreeting($language: String!) {greeting(language: $language) {message}}`;function Hello() {const [loadGreeting, { called, loading, data }] = useLazyQuery(GET_GREETING,{ variables: { language: "english" } });if (called && loading) return <p>Loading ...</p>if (!called) {return <button onClick={() => loadGreeting()}>Load greeting</button>}return <h1>Hello {data.greeting.message}!</h1>;}3.0.0
function useLoadableQuery
useLoadableQuery: { < TData, TVariables extends OperationVariables, TOptions extends LoadableQueryHookOptions >( query: DocumentNode | TypedDocumentNode<TData, TVariables>, options?: LoadableQueryHookOptions & TOptions ): UseLoadableQueryResult< TOptions['errorPolicy'] extends 'all' | 'ignore' ? TOptions['returnPartialData'] extends true ? DeepPartial<TData> : TData : TOptions['returnPartialData'] extends true ? DeepPartial<TData> : TData, TVariables >; <TData = unknown, TVariables extends OperationVariables = OperationVariables>( query: any, options: LoadableQueryHookOptions & { returnPartialData: true; errorPolicy: 'all' | 'ignore'; } ): UseLoadableQueryResult<DeepPartial<TData>, TVariables>; <TData = unknown, TVariables extends OperationVariables = OperationVariables>( query: any, options: LoadableQueryHookOptions & { errorPolicy: 'all' | 'ignore' } ): UseLoadableQueryResult<TData, TVariables>; <TData = unknown, TVariables extends OperationVariables = OperationVariables>( query: any, options: LoadableQueryHookOptions & { returnPartialData: true } ): UseLoadableQueryResult<DeepPartial<TData>, TVariables>; <TData = unknown, TVariables extends OperationVariables = OperationVariables>( query: any, options?: LoadableQueryHookOptions ): UseLoadableQueryResult<TData, TVariables>;};
A hook for imperatively loading a query, such as responding to a user interaction.
> Refer to the [Suspense - Fetching in response to user interaction](https://www.apollographql.com/docs/react/data/suspense#fetching-in-response-to-user-interaction) section for a more in-depth overview of
useLoadableQuery
.Parameter query
A GraphQL query document parsed into an AST by
gql
.Parameter options
Options to control how the query is executed.
Returns
A tuple in the form of
[loadQuery, queryRef, handlers]
Example 1
import { gql, useLoadableQuery } from "@apollo/client";const GET_GREETING = gql`query GetGreeting($language: String!) {greeting(language: $language) {message}}`;function App() {const [loadGreeting, queryRef] = useLoadableQuery(GET_GREETING);return (<><button onClick={() => loadGreeting({ language: "english" })}>Load greeting</button><Suspense fallback={<div>Loading...</div>}>{queryRef && <Hello queryRef={queryRef} />}</Suspense></>);}function Hello({ queryRef }) {const { data } = useReadQuery(queryRef);return <div>{data.greeting.message}</div>;}3.9.0
function useMutation
useMutation: < TData = any, TVariables = OperationVariables, TContext = DefaultContext, TCache extends ApolloCache<any> = ApolloCache<any>>( mutation: DocumentNode | TypedDocumentNode<TData, TVariables>, options?: MutationHookOptions< NoInfer<TData>, NoInfer<TVariables>, TContext, TCache >) => MutationTuple<TData, TVariables, TContext, TCache>;
> Refer to the [Mutations](https://www.apollographql.com/docs/react/data/mutations/) section for a more in-depth overview of
useMutation
.Parameter mutation
A GraphQL mutation document parsed into an AST by
gql
.Parameter options
Options to control how the mutation is executed.
Returns
A tuple in the form of
[mutate, result]
Example 1
import { gql, useMutation } from '@apollo/client';const ADD_TODO = gql`mutation AddTodo($type: String!) {addTodo(type: $type) {idtype}}`;function AddTodo() {let input;const [addTodo, { data }] = useMutation(ADD_TODO);return (<div><formonSubmit={e => {e.preventDefault();addTodo({ variables: { type: input.value } });input.value = '';}}><inputref={node => {input = node;}}/><button type="submit">Add Todo</button></form></div>);}3.0.0
function useQuery
useQuery: < TData = any, TVariables extends OperationVariables = OperationVariables>( query: DocumentNode | TypedDocumentNode<TData, TVariables>, options?: QueryHookOptions<NoInfer<TData>, NoInfer<TVariables>>) => QueryResult<TData, TVariables>;
A hook for executing queries in an Apollo application.
To run a query within a React component, call
useQuery
and pass it a GraphQL query document.When your component renders,
useQuery
returns an object from Apollo Client that containsloading
,error
, anddata
properties you can use to render your UI.> Refer to the [Queries](https://www.apollographql.com/docs/react/data/queries) section for a more in-depth overview of
useQuery
.Parameter query
A GraphQL query document parsed into an AST by
gql
.Parameter options
Options to control how the query is executed.
Returns
Query result object
Example 1
import { gql, useQuery } from '@apollo/client';const GET_GREETING = gql`query GetGreeting($language: String!) {greeting(language: $language) {message}}`;function Hello() {const { loading, error, data } = useQuery(GET_GREETING, {variables: { language: 'english' },});if (loading) return <p>Loading ...</p>;return <h1>Hello {data.greeting.message}!</h1>;}3.0.0
function useQueryRefHandlers
useQueryRefHandlers: < TData = unknown, TVariables extends OperationVariables = OperationVariables>( queryRef: QueryRef<TData, TVariables>) => UseQueryRefHandlersResult<TData, TVariables>;
A React hook that returns a
refetch
andfetchMore
function for a givenqueryRef
.This is useful to get access to handlers for a
queryRef
that was created bycreateQueryPreloader
or when the handlers for aqueryRef
produced in a different component are inaccessible.Parameter queryRef
A
QueryRef
returned fromuseBackgroundQuery
,useLoadableQuery
, orcreateQueryPreloader
.Example 1
const MyComponent({ queryRef }) {const { refetch, fetchMore } = useQueryRefHandlers(queryRef);// ...}3.9.0
function useReactiveVar
useReactiveVar: <T>(rv: ReactiveVar<T>) => T;
Reads the value of a [reactive variable](https://www.apollographql.com/docs/react/local-state/reactive-variables/) and re-renders the containing component whenever that variable's value changes. This enables a reactive variable to trigger changes _without_ relying on the
useQuery
hook.Parameter rv
A reactive variable.
Returns
The current value of the reactive variable.
Example 1
import { makeVar, useReactiveVar } from "@apollo/client";export const cartItemsVar = makeVar([]);export function Cart() {const cartItems = useReactiveVar(cartItemsVar);// ...}3.2.0
function useReadQuery
useReadQuery: <TData>(queryRef: QueryRef<TData>) => UseReadQueryResult<TData>;
function useSubscription
useSubscription: < TData = any, TVariables extends OperationVariables = OperationVariables>( subscription: DocumentNode | TypedDocumentNode<TData, TVariables>, options?: SubscriptionHookOptions<NoInfer<TData>, NoInfer<TVariables>>) => { restart: () => void; loading: boolean; data?: TData | undefined; error?: ApolloError; variables?: TVariables | undefined;};
> Refer to the [Subscriptions](https://www.apollographql.com/docs/react/data/subscriptions/) section for a more in-depth overview of
useSubscription
.Parameter subscription
A GraphQL subscription document parsed into an AST by
gql
.Parameter options
Options to control how the subscription is executed.
Returns
Query result object
Remarks
#### Consider using
onData
instead ofuseEffect
If you want to react to incoming data, please use the
onData
option instead ofuseEffect
. State updates you make inside auseEffect
hook might cause additional rerenders, anduseEffect
is mostly meant for side effects of rendering, not as an event handler. State updates made in an event handler likeonData
might - depending on the React version - be batched and cause only a single rerender.Consider the following component:
export function Subscriptions() {const { data, error, loading } = useSubscription(query);const [accumulatedData, setAccumulatedData] = useState([]);useEffect(() => {setAccumulatedData((prev) => [...prev, data]);}, [data]);return (<>{loading && <p>Loading...</p>}{JSON.stringify(accumulatedData, undefined, 2)}</>);}Instead of using
useEffect
here, we can re-write this component to use theonData
callback function accepted inuseSubscription
'soptions
object:export function Subscriptions() {const [accumulatedData, setAccumulatedData] = useState([]);const { data, error, loading } = useSubscription(query,{onData({ data }) {setAccumulatedData((prev) => [...prev, data])}});return (<>{loading && <p>Loading...</p>}{JSON.stringify(accumulatedData, undefined, 2)}</>);}> ⚠️ **Note:** The
useSubscription
optiononData
is available in Apollo Client >= 3.7. In previous versions, the equivalent option is namedonSubscriptionData
.Now, the first message will be added to the
accumulatedData
array sinceonData
is called _before_ the component re-renders. React 18 automatic batching is still in effect and results in a single re-render, but withonData
we can guarantee each message received after the component mounts is added toaccumulatedData
.3.0.0
Example 1
const COMMENTS_SUBSCRIPTION = gql`subscription OnCommentAdded($repoFullName: String!) {commentAdded(repoFullName: $repoFullName) {idcontent}}`;function DontReadTheComments({ repoFullName }) {const {data: { commentAdded },loading,} = useSubscription(COMMENTS_SUBSCRIPTION, { variables: { repoFullName } });return <h4>New comment: {!loading && commentAdded.content}</h4>;}
function useSuspenseFragment
useSuspenseFragment: { <TData, TVariables extends OperationVariables = OperationVariables>( options: UseSuspenseFragmentOptions<TData, TVariables> & { from: NonNullable<From<TData>>; } ): UseSuspenseFragmentResult<TData>; <TData, TVariables extends OperationVariables = OperationVariables>( options: { fragment: any; fragmentName?: string; from: From<TData>; optimistic?: boolean; client?: ApolloClient<any>; } & VariablesOption<NoInfer<TVariables>> & { from: null } ): UseSuspenseFragmentResult<null>; <TData, TVariables extends OperationVariables = OperationVariables>( options: { fragment: any; fragmentName?: string; from: From<TData>; optimistic?: boolean; client?: ApolloClient<any>; } & VariablesOption<NoInfer<TVariables>> & { from: From<TData> } ): UseSuspenseFragmentResult<TData>; <TData, TVariables extends OperationVariables = OperationVariables>( options: UseSuspenseFragmentOptions<TData, TVariables> ): UseSuspenseFragmentResult<TData>;};
function useSuspenseQuery
useSuspenseQuery: { < TData, TVariables extends OperationVariables, TOptions extends Omit< SuspenseQueryHookOptions<TData, OperationVariables>, 'variables' > >( query: DocumentNode | TypedDocumentNode<TData, TVariables>, options?: SuspenseQueryHookOptions<NoInfer<TData>, NoInfer<TVariables>> & TOptions ): UseSuspenseQueryResult< TOptions['errorPolicy'] extends 'ignore' | 'all' ? TOptions['returnPartialData'] extends true ? DeepPartial<TData> | undefined : TData | undefined : TOptions['returnPartialData'] extends true ? TOptions['skip'] extends boolean ? DeepPartial<TData> | undefined : DeepPartial<TData> : TOptions['skip'] extends boolean ? TData | undefined : TData, TVariables >; <TData = unknown, TVariables extends OperationVariables = OperationVariables>( query: any, options: SuspenseQueryHookOptions<NoInfer<TData>, NoInfer<TVariables>> & { returnPartialData: true; errorPolicy: 'all' | 'ignore'; } ): UseSuspenseQueryResult<DeepPartial<TData>, TVariables>; <TData = unknown, TVariables extends OperationVariables = OperationVariables>( query: any, options: SuspenseQueryHookOptions<NoInfer<TData>, NoInfer<TVariables>> & { errorPolicy: 'all' | 'ignore'; } ): UseSuspenseQueryResult<TData, TVariables>; <TData = unknown, TVariables extends OperationVariables = OperationVariables>( query: any, options: SuspenseQueryHookOptions<NoInfer<TData>, NoInfer<TVariables>> & { skip: boolean; returnPartialData: true; } ): UseSuspenseQueryResult<DeepPartial<TData>, TVariables>; <TData = unknown, TVariables extends OperationVariables = OperationVariables>( query: any, options: SuspenseQueryHookOptions<NoInfer<TData>, NoInfer<TVariables>> & { returnPartialData: true; } ): UseSuspenseQueryResult<DeepPartial<TData>, TVariables>; <TData = unknown, TVariables extends OperationVariables = OperationVariables>( query: any, options: SuspenseQueryHookOptions<NoInfer<TData>, NoInfer<TVariables>> & { skip: boolean; } ): UseSuspenseQueryResult<TData, TVariables>; <TData = unknown, TVariables extends OperationVariables = OperationVariables>( query: any, options?: SuspenseQueryHookOptions<NoInfer<TData>, NoInfer<TVariables>> ): UseSuspenseQueryResult<TData, TVariables>; <TData = unknown, TVariables extends OperationVariables = OperationVariables>( query: any, options: | typeof skipToken | (SuspenseQueryHookOptions<NoInfer<TData>, NoInfer<TVariables>> & { returnPartialData: true; }) ): UseSuspenseQueryResult<DeepPartial<TData>, TVariables>; <TData = unknown, TVariables extends OperationVariables = OperationVariables>( query: any, options?: | typeof skipToken | SuspenseQueryHookOptions<NoInfer<TData>, NoInfer<TVariables>> ): UseSuspenseQueryResult<TData, TVariables>;};
Classes
class ApolloCache
abstract class ApolloCache<TSerialized> implements DataProxy {}
property assumeImmutableResults
readonly assumeImmutableResults: boolean;
method batch
batch: <U>(options: Cache.BatchOptions<this, U>) => U;
method diff
abstract diff: <T>(query: Cache.DiffOptions) => Cache.DiffResult<T>;
method evict
abstract evict: (options: Cache.EvictOptions) => boolean;
method extract
abstract extract: (optimistic?: boolean) => TSerialized;
Exposes the cache's complete state, in a serializable format for later restoration.
method fragmentMatches
fragmentMatches: (fragment: InlineFragmentNode, typename: string) => boolean;
method gc
gc: () => string[];
method identify
identify: (object: StoreObject | Reference) => string | undefined;
method lookupFragment
lookupFragment: (fragmentName: string) => FragmentDefinitionNode | null;
method modify
modify: <Entity extends Record<string, any> = Record<string, any>>( options: Cache.ModifyOptions<Entity>) => boolean;
method performTransaction
abstract performTransaction: ( transaction: Transaction<TSerialized>, optimisticId?: string | null) => void;
method read
abstract read: <TData = any, TVariables = any>( query: Cache.ReadOptions<TVariables, TData>) => Unmasked<TData> | null;
method readFragment
readFragment: <FragmentType, TVariables = any>( options: Cache.ReadFragmentOptions<FragmentType, TVariables>, optimistic?: boolean) => Unmasked<FragmentType> | null;
method readQuery
readQuery: <QueryType, TVariables = any>( options: Cache.ReadQueryOptions<QueryType, TVariables>, optimistic?: boolean) => Unmasked<QueryType> | null;
method recordOptimisticTransaction
recordOptimisticTransaction: ( transaction: Transaction<TSerialized>, optimisticId: string) => void;
method removeOptimistic
abstract removeOptimistic: (id: string) => void;
method reset
abstract reset: (options?: Cache.ResetOptions) => Promise<void>;
method restore
abstract restore: (serializedState: TSerialized) => ApolloCache<TSerialized>;
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.
method transformDocument
transformDocument: (document: DocumentNode) => DocumentNode;
method transformForLink
transformForLink: (document: DocumentNode) => DocumentNode;
method updateFragment
updateFragment: <TData = any, TVariables = any>( options: Cache.UpdateFragmentOptions<TData, TVariables>, update: (data: Unmasked<TData> | null) => Unmasked<TData> | null | void) => Unmasked<TData> | null;
method updateQuery
updateQuery: <TData = any, TVariables = any>( options: Cache.UpdateQueryOptions<TData, TVariables>, update: (data: Unmasked<TData> | null) => Unmasked<TData> | null | void) => Unmasked<TData> | null;
method watch
abstract watch: <TData = any, TVariables = any>( watch: Cache.WatchOptions<TData, TVariables>) => () => void;
method watchFragment
watchFragment: <TData = any, TVars = OperationVariables>( options: WatchFragmentOptions<TData, TVars>) => Observable<WatchFragmentResult<TData>>;
Watches the cache store of the fragment according to the options specified and returns an
Observable
. We can subscribe to thisObservable
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
.Parameter options
An object of type
WatchFragmentOptions
that allows the cache to identify the fragment and optionally specify whether to react to optimistic updates.3.10.0
method write
abstract write: <TData = any, TVariables = any>( write: Cache.WriteOptions<TData, TVariables>) => Reference | undefined;
method writeFragment
writeFragment: <TData = any, TVariables = any>({ id, data, fragment, fragmentName, ...options}: Cache.WriteFragmentOptions<TData, TVariables>) => Reference | undefined;
method writeQuery
writeQuery: <TData = any, TVariables = any>({ id, data, ...options}: Cache.WriteQueryOptions<TData, TVariables>) => Reference | undefined;
class ApolloClient
class ApolloClient<TCacheShape> implements DataProxy {}
This is the primary Apollo Client class. It is used to send GraphQL documents (i.e. queries and mutations) to a GraphQL spec-compliant server over an
ApolloLink
instance, receive results from the server and cache the results in a store. It also delivers updates to GraphQL queries throughObservable
instances.
constructor
constructor(options: ApolloClientOptions<TCacheShape>);
Constructs an instance of
ApolloClient
.Example 1
import { ApolloClient, InMemoryCache } from '@apollo/client';const cache = new InMemoryCache();const client = new ApolloClient({// Provide required constructor fieldscache: cache,uri: 'http://localhost:4000/',// Provide some optional constructor fieldsname: 'react-web-client',version: '1.3',queryDeduplication: false,defaultOptions: {watchQuery: {fetchPolicy: 'cache-and-network',},},});
property cache
cache: ApolloCache<TCacheShape>;
property defaultContext
readonly defaultContext: Partial<DefaultContext>;
property defaultOptions
defaultOptions: DefaultOptions;
property devtoolsConfig
readonly devtoolsConfig: DevtoolsOptions;
property disableNetworkFetches
disableNetworkFetches: boolean;
property documentTransform
readonly documentTransform: DocumentTransform;
The
DocumentTransform
used to modify GraphQL documents before a request is made. If a customDocumentTransform
is not provided, this will be the default document transform.
property getMemoryInternals
getMemoryInternals?: () => { limits: { [k: string]: number }; sizes: { cache?: { fragmentQueryDocuments: number }; addTypenameDocumentTransform?: { cache: number }[]; inMemoryCache?: { executeSelectionSet: number; executeSubSelectedArray: number; maybeBroadcastWatch: number; }; fragmentRegistry?: { findFragmentSpreads: number; lookup: number; transform: number; }; print: number; parser: number; canonicalStringify: number; links: unknown[]; queryManager: { getDocumentInfo: number; documentTransforms: { cache: number }[]; }; };};
This is not a stable API - it is used in development builds to expose information to the DevTools. Use at your own risk! For more details, see [Memory Management](https://www.apollographql.com/docs/react/caching/memory-management/#measuring-cache-usage)
Example 1
console.log(client.getMemoryInternals())Logs output in the following JSON format:
Example 2
{limits: {parser: 1000,canonicalStringify: 1000,print: 2000,'documentTransform.cache': 2000,'queryManager.getDocumentInfo': 2000,'PersistedQueryLink.persistedQueryHashes': 2000,'fragmentRegistry.transform': 2000,'fragmentRegistry.lookup': 1000,'fragmentRegistry.findFragmentSpreads': 4000,'cache.fragmentQueryDocuments': 1000,'removeTypenameFromVariables.getVariableDefinitions': 2000,'inMemoryCache.maybeBroadcastWatch': 5000,'inMemoryCache.executeSelectionSet': 10000,'inMemoryCache.executeSubSelectedArray': 5000},sizes: {parser: 26,canonicalStringify: 4,print: 14,addTypenameDocumentTransform: [{cache: 14,},],queryManager: {getDocumentInfo: 14,documentTransforms: [{cache: 14,},{cache: 14,},],},fragmentRegistry: {findFragmentSpreads: 34,lookup: 20,transform: 14,},cache: {fragmentQueryDocuments: 22,},inMemoryCache: {executeSelectionSet: 4345,executeSubSelectedArray: 1206,maybeBroadcastWatch: 32,},links: [{PersistedQueryLink: {persistedQueryHashes: 14,},},{removeTypenameFromVariables: {getVariableDefinitions: 14,},},],},}Modifiers
@experimental
property link
link: ApolloLink;
property queryDeduplication
queryDeduplication: boolean;
property typeDefs
readonly typeDefs: any;
property version
version: string;
method addResolvers
addResolvers: (resolvers: Resolvers | Resolvers[]) => void;
Add additional local resolvers.
method clearStore
clearStore: () => Promise<any[]>;
Remove all data from the store. Unlike
resetStore
,clearStore
will not refetch any active queries.
method extract
extract: (optimistic?: boolean) => TCacheShape;
Exposes the cache's complete state, in a serializable format for later restoration.
method getObservableQueries
getObservableQueries: ( include?: RefetchQueriesInclude) => Map<string, ObservableQuery<any>>;
Get all currently active
ObservableQuery
objects, in aMap
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.
method getResolvers
getResolvers: () => Resolvers;
Get all registered local resolvers.
method mutate
mutate: < TData = any, TVariables extends OperationVariables = OperationVariables, TContext extends Record<string, any> = DefaultContext, TCache extends ApolloCache<any> = ApolloCache<any>>( options: MutationOptions<TData, TVariables, TContext>) => Promise<FetchResult<MaybeMasked<TData>>>;
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
anderrors
might be undefined, for example whenerrorPolicy
is set to'ignore'
.It takes options as an object with the following keys and values:
method onClearStore
onClearStore: (cb: () => Promise<any>) => () => void;
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.
method onResetStore
onResetStore: (cb: () => Promise<any>) => () => void;
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.
method query
query: <T = any, TVariables extends OperationVariables = OperationVariables>( options: QueryOptions<TVariables, T>) => Promise<ApolloQueryResult<MaybeMasked<T>>>;
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.Parameter options
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.
method readFragment
readFragment: <T = any, TVariables = OperationVariables>( options: DataProxy.Fragment<TVariables, T>, optimistic?: boolean) => Unmasked<T> | 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
.Parameter optimistic
Set to
true
to allowreadFragment
to return optimistic results. Isfalse
by default.
method readQuery
readQuery: <T = any, TVariables = OperationVariables>( options: DataProxy.Query<TVariables, T>, optimistic?: boolean) => Unmasked<T> | null;
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
usereadFragment
.Parameter optimistic
Set to
true
to allowreadQuery
to return optimistic results. Isfalse
by default.
method reFetchObservableQueries
reFetchObservableQueries: ( includeStandby?: boolean) => Promise<ApolloQueryResult<any>[]>;
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 outageIt 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 parameterincludeStandby
which will include queries in standby-mode when refetching.
method refetchQueries
refetchQueries: < TCache extends ApolloCache<any> = ApolloCache<TCacheShape>, TResult = Promise<ApolloQueryResult<any>>>( options: RefetchQueriesOptions<TCache, TResult>) => RefetchQueriesResult<TResult>;
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.
method resetStore
resetStore: () => Promise<ApolloQueryResult<any>[] | null>;
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.
method restore
restore: (serializedState: TCacheShape) => ApolloCache<TCacheShape>;
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.
method setLink
setLink: (newLink: ApolloLink) => void;
Define a new ApolloLink (or link chain) that Apollo Client will use.
method setLocalStateFragmentMatcher
setLocalStateFragmentMatcher: (fragmentMatcher: FragmentMatcher) => void;
Set a custom local state fragment matcher.
method setResolvers
setResolvers: (resolvers: Resolvers | Resolvers[]) => void;
Set (override existing) local resolvers.
method stop
stop: () => void;
Call this method to terminate any active client processes, making it safe to dispose of this
ApolloClient
instance.
method subscribe
subscribe: <T = any, TVariables extends OperationVariables = OperationVariables>( options: SubscriptionOptions<TVariables, T>) => Observable<FetchResult<T, Record<string, any>, Record<string, any>>>;
This subscribes to a graphql subscription according to the options specified and returns an
Observable
which either emits received data or an error.
method watchFragment
watchFragment: <TFragmentData = unknown, TVariables = OperationVariables>( options: WatchFragmentOptions<TFragmentData, TVariables>) => Observable<WatchFragmentResult<TFragmentData>>;
Watches the cache store of the fragment according to the options specified and returns an
Observable
. We can subscribe to thisObservable
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
.3.10.0
Parameter options
An object of type
WatchFragmentOptions
that allows the cache to identify the fragment and optionally specify whether to react to optimistic updates.
method watchQuery
watchQuery: < T = any, TVariables extends OperationVariables = OperationVariables>( options: WatchQueryOptions<TVariables, T>) => ObservableQuery<T, TVariables>;
This watches the cache store of the query according to the options specified and returns an
ObservableQuery
. We can subscribe to thisObservableQuery
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](https://medium.com/apollo-stack/the-concepts-of-graphql-bc68bd819be3#.3mb0cbcmc) for a description of store reactivity.
method writeFragment
writeFragment: <TData = any, TVariables = OperationVariables>( options: DataProxy.WriteFragmentOptions<TData, TVariables>) => 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
.
method writeQuery
writeQuery: <TData = any, TVariables = OperationVariables>( options: DataProxy.WriteQueryOptions<TData, TVariables>) => Reference | undefined;
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 usewriteFragment
.
class ApolloError
class ApolloError extends Error {}
constructor
constructor({ graphQLErrors, protocolErrors, clientErrors, networkError, errorMessage, extraInfo,}: ApolloErrorOptions);
property cause
cause: { readonly message: string; extensions?: GraphQLErrorExtensions[] | GraphQLFormattedError['extensions'];} & Omit<any, 'extensions'>;
Indicates the specific original cause of the error.
This field contains the first available
networkError
,graphQLError
,protocolError
,clientError
, ornull
if none are available.
property clientErrors
clientErrors: readonly Error[];
property extraInfo
extraInfo: any;
property graphQLErrors
graphQLErrors: readonly GraphQLFormattedError[];
property message
message: string;
property name
name: string;
property networkError
networkError: Error | ServerParseError | ServerError;
property protocolErrors
protocolErrors: readonly GraphQLFormattedError[];
class ApolloLink
class ApolloLink {}
constructor
constructor(request?: RequestHandler);
method concat
static concat: ( first: ApolloLink | RequestHandler, second: ApolloLink | RequestHandler) => ApolloLink;
method empty
static empty: () => ApolloLink;
method execute
static execute: ( link: ApolloLink, operation: GraphQLRequest) => Observable< FetchResult<Record<string, any>, Record<string, any>, Record<string, any>>>;
method from
static from: (links: (ApolloLink | RequestHandler)[]) => ApolloLink;
method onError
protected onError: ( error: any, observer?: Observer< FetchResult< Record<string, any>, Record<string, any>, Record<string, any> > >) => false | void;
method request
request: ( operation: Operation, forward?: NextLink) => Observable<FetchResult> | null;
method setOnError
setOnError: (fn: ApolloLink['onError']) => this;
method split
static split: ( test: (op: Operation) => boolean, left: ApolloLink | RequestHandler, right?: ApolloLink | RequestHandler) => ApolloLink;
class DocumentTransform
class DocumentTransform {}
constructor
constructor(transform: TransformFn, options?: DocumentTransformOptions);
method concat
concat: (otherTransform: DocumentTransform) => DocumentTransform;
method identity
static identity: () => DocumentTransform;
method resetCache
resetCache: () => void;
Resets the internal cache of this transform, if it has one.
method split
static split: ( predicate: (document: DocumentNode) => boolean, left: DocumentTransform, right?: DocumentTransform) => DocumentTransform & { left: DocumentTransform; right: DocumentTransform };
method transformDocument
transformDocument: (document: DocumentNode) => DocumentNode;
class HttpLink
class HttpLink extends ApolloLink {}
constructor
constructor(options?: HttpOptions);
property options
options: HttpOptions;
class InMemoryCache
class InMemoryCache extends ApolloCache<NormalizedCacheObject> {}
constructor
constructor(config?: InMemoryCacheConfig);
property assumeImmutableResults
readonly assumeImmutableResults: boolean;
property config
protected config: InMemoryCacheConfig;
property makeVar
readonly makeVar: <T>(value: T) => ReactiveVar<T>;
property policies
readonly policies: Policies;
method batch
batch: <TUpdateResult>( options: Cache.BatchOptions<InMemoryCache, TUpdateResult>) => TUpdateResult;
method broadcastWatches
protected broadcastWatches: (options?: BroadcastOptions) => void;
method diff
diff: <TData, TVariables extends OperationVariables = any>( options: Cache.DiffOptions<TData, TVariables>) => Cache.DiffResult<TData>;
method evict
evict: (options: Cache.EvictOptions) => boolean;
method extract
extract: (optimistic?: boolean) => NormalizedCacheObject;
method fragmentMatches
fragmentMatches: (fragment: InlineFragmentNode, typename: string) => boolean;
method gc
gc: (options?: { resetResultCache?: boolean; resetResultIdentities?: boolean;}) => string[];
method identify
identify: (object: StoreObject | Reference) => string | undefined;
method lookupFragment
lookupFragment: (fragmentName: string) => FragmentDefinitionNode | null;
method modify
modify: <Entity extends Record<string, any> = Record<string, any>>( options: Cache.ModifyOptions<Entity>) => boolean;
method performTransaction
performTransaction: ( update: (cache: InMemoryCache) => any, optimisticId?: string | null) => any;
method read
read: <T>(options: Cache.ReadOptions) => T | null;
method release
release: (rootId: string, optimistic?: boolean) => number;
method removeOptimistic
removeOptimistic: (idToRemove: string) => void;
method reset
reset: (options?: Cache.ResetOptions) => Promise<void>;
method restore
restore: (data: NormalizedCacheObject) => this;
method retain
retain: (rootId: string, optimistic?: boolean) => number;
method transformDocument
transformDocument: (document: DocumentNode) => DocumentNode;
method watch
watch: <TData = any, TVariables = any>( watch: Cache.WatchOptions<TData, TVariables>) => () => void;
method write
write: (options: Cache.WriteOptions) => Reference | undefined;
class MissingFieldError
class MissingFieldError extends Error {}
constructor
constructor( message: string, path: MissingTree | (string | number)[], query: DocumentNode, variables?: Record<string, any>);
property message
readonly message: string;
property missing
readonly missing: MissingTree;
property path
readonly path: MissingTree | (string | number)[];
property query
readonly query: DocumentNode;
property variables
readonly variables?: Record<string, any>;
class ObservableQuery
class ObservableQuery< TData = any, TVariables extends OperationVariables = OperationVariables> extends Observable<ApolloQueryResult<MaybeMasked<TData>>> {}
constructor
constructor({ queryManager, queryInfo, options,}: { queryManager: QueryManager<any>; queryInfo: QueryInfo; options: WatchQueryOptions<TVariables, TData>;});
property options
readonly options: WatchQueryOptions<TVariables, TData>;
property query
readonly query: TypedDocumentNode<TData, TVariables>;
property queryId
readonly queryId: string;
property queryName
readonly queryName?: string;
property variables
readonly variables: OperationVariables;
An object containing the variables that were provided for the query.
method fetchMore
fetchMore: < TFetchData = TData, TFetchVars extends OperationVariables = TVariables>( fetchMoreOptions: FetchMoreQueryOptions<TFetchVars, TFetchData> & { updateQuery?: ( previousQueryResult: Unmasked<TData>, options: { fetchMoreResult: Unmasked<TFetchData>; variables: TFetchVars; } ) => Unmasked<TData>; }) => Promise<ApolloQueryResult<MaybeMasked<TFetchData>>>;
A function that helps you fetch the next set of results for a [paginated list field](https://www.apollographql.com/docs/react/pagination/core-api/).
method getCurrentResult
getCurrentResult: ( saveAsLastResult?: boolean) => ApolloQueryResult<MaybeMasked<TData>>;
method getLastError
getLastError: (variablesMustMatch?: boolean) => ApolloError | undefined;
method getLastResult
getLastResult: ( variablesMustMatch?: boolean) => ApolloQueryResult<TData> | undefined;
method hasObservers
hasObservers: () => boolean;
method isDifferentFromLastResult
isDifferentFromLastResult: ( newResult: ApolloQueryResult<TData>, variables?: TVariables) => boolean | undefined;
method refetch
refetch: ( variables?: Partial<TVariables>) => Promise<ApolloQueryResult<MaybeMasked<TData>>>;
Update the variables of this observable query, and fetch the new results. This method should be preferred over
setVariables
in most use cases.Parameter variables
The new set of variables. If there are missing variables, the previous values of those variables will be used.
method reobserve
reobserve: ( newOptions?: Partial<WatchQueryOptions<TVariables, TData>>, newNetworkStatus?: NetworkStatus) => Promise<ApolloQueryResult<MaybeMasked<TData>>>;
method reobserveAsConcast
reobserveAsConcast: ( newOptions?: Partial<WatchQueryOptions<TVariables, TData>>, newNetworkStatus?: NetworkStatus) => Concast<ApolloQueryResult<TData>>;
method resetLastResults
resetLastResults: () => void;
method resetQueryStoreErrors
resetQueryStoreErrors: () => void;
method resubscribeAfterError
resubscribeAfterError: { ( onNext: (value: ApolloQueryResult<MaybeMasked<TData>>) => void, onError?: (error: any) => void, onComplete?: () => void ): ObservableSubscription; (observer: Observer<ApolloQueryResult<TData>>): ObservableSubscription;};
method result
result: () => Promise<ApolloQueryResult<MaybeMasked<TData>>>;
method setOptions
setOptions: ( newOptions: Partial<WatchQueryOptions<TVariables, TData>>) => Promise<ApolloQueryResult<MaybeMasked<TData>>>;
method setVariables
setVariables: ( variables: TVariables) => Promise<ApolloQueryResult<MaybeMasked<TData>> | void>;
Update the variables of this observable query, and fetch the new results if they've changed. Most users should prefer
refetch
instead ofsetVariables
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).
Parameter variables
The new set of variables. If there are missing variables, the previous values of those variables will be used.
method silentSetOptions
silentSetOptions: ( newOptions: Partial<WatchQueryOptions<TVariables, TData>>) => void;
method startPolling
startPolling: (pollInterval: number) => void;
A function that instructs the query to begin re-executing at a specified interval (in milliseconds).
method stopPolling
stopPolling: () => void;
A function that instructs the query to stop polling after a previous call to
startPolling
.
method subscribeToMore
subscribeToMore: < TSubscriptionData = TData, TSubscriptionVariables extends OperationVariables = TVariables>( options: SubscribeToMoreOptions< TData, TSubscriptionVariables, TSubscriptionData, TVariables >) => () => void;
A function that enables you to execute a [subscription](https://www.apollographql.com/docs/react/data/subscriptions/), 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.
method updateQuery
updateQuery: (mapFn: UpdateQueryMapFn<TData, TVariables>) => void;
A function that enables you to update the query's cached result without executing a followup GraphQL operation.
See [using updateQuery and updateFragment](https://www.apollographql.com/docs/react/caching/cache-interaction/#using-updatequery-and-updatefragment) for additional information.
Interfaces
interface ApolloClientOptions
interface ApolloClientOptions<TCacheShape> {}
property assumeImmutableResults
assumeImmutableResults?: boolean;
If
true
, Apollo Client will assume results read from the cache are never mutated by application code, which enables substantial performance optimizations.
property cache
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](https://www.apollographql.com/docs/react/caching/cache-configuration/).
property connectToDevTools
connectToDevTools?: boolean;
If
true
, the [Apollo Client Devtools](https://www.apollographql.com/docs/react/development-testing/developer-tooling/#apollo-client-devtools) browser extension can connect to Apollo Client.The default value is
false
in production andtrue
in development (if there is awindow
object).Deprecated
Please use the
devtools.enabled
option.
property credentials
credentials?: string;
property dataMasking
dataMasking?: boolean;
Determines if data masking is enabled for the client.
property defaultContext
defaultContext?: Partial<DefaultContext>;
property defaultOptions
defaultOptions?: DefaultOptions;
Provide this object to set application-wide default values for options you can provide to the
watchQuery
,query
, andmutate
functions. See below for an example object.See this [example object](https://www.apollographql.com/docs/react/api/core/ApolloClient#example-defaultoptions-object).
property devtools
devtools?: DevtoolsOptions;
Configuration used by the [Apollo Client Devtools extension](https://www.apollographql.com/docs/react/development-testing/developer-tooling/#apollo-client-devtools) for this client.
3.11.0
property documentTransform
documentTransform?: DocumentTransform;
property fragmentMatcher
fragmentMatcher?: FragmentMatcher;
property headers
headers?: 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.
property link
link?: ApolloLink;
You can provide an
ApolloLink
instance to serve as Apollo Client's network layer. For more information, see [Advanced HTTP networking](https://www.apollographql.com/docs/react/networking/advanced-http-networking/).One of
uri
orlink
is **required**. If you provide both,link
takes precedence.
property name
name?: 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](https://www.apollographql.com/docs/apollo-server/monitoring/metrics#identifying-distinct-clients) feature.
property queryDeduplication
queryDeduplication?: 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.
property resolvers
resolvers?: Resolvers | Resolvers[];
property ssrForceFetchDelay
ssrForceFetchDelay?: number;
The time interval (in milliseconds) before Apollo Client force-fetches queries after a server-side render.
property ssrMode
ssrMode?: boolean;
When using Apollo Client for [server-side rendering](https://www.apollographql.com/docs/react/performance/server-side-rendering/), set this to
true
so that the [getDataFromTree
function](../react/ssr/#getdatafromtree) can work effectively.
property typeDefs
typeDefs?: string | string[] | DocumentNode | DocumentNode[];
property uri
uri?: string | UriFunction;
The URI of the GraphQL endpoint that Apollo Client will communicate with.
One of
uri
orlink
is **required**. If you provide both,link
takes precedence.
property version
version?: 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](https://www.apollographql.com/docs/apollo-server/monitoring/metrics#identifying-distinct-clients) 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.
interface ApolloContextValue
interface ApolloContextValue {}
property client
client?: ApolloClient<object>;
property renderPromises
renderPromises?: RenderPromises;
interface ApolloPayloadResult
interface ApolloPayloadResult< TData = Record<string, any>, TExtensions = Record<string, any>> {}
interface ApolloQueryResult
interface ApolloQueryResult<T> {}
property data
data: T;
property error
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.
property errors
errors?: ReadonlyArray<GraphQLFormattedError>;
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.
property loading
loading: boolean;
property networkStatus
networkStatus: NetworkStatus;
property partial
partial?: boolean;
interface BackgroundQueryHookOptions
interface BackgroundQueryHookOptions< TData = unknown, TVariables extends OperationVariables = OperationVariables> extends Pick< QueryHookOptions<TData, TVariables>, | 'client' | 'variables' | 'errorPolicy' | 'context' | 'canonizeResults' | 'returnPartialData' | 'refetchWritePolicy' > {}
property fetchPolicy
fetchPolicy?: BackgroundQueryHookFetchPolicy;
property queryKey
queryKey?: string | number | any[];
property skip
skip?: boolean;
If
true
, the query is not executed. The default value isfalse
.Example 1
Recommended usage of
skipToken
:import { skipToken, useBackgroundQuery } from '@apollo/client';const [queryRef] = useBackgroundQuery(query, id ? { variables: { id } } : skipToken);Deprecated
We recommend using
skipToken
in place of theskip
option as it is more type-safe.This option is deprecated and only supported to ease the migration from useQuery. It will be removed in a future release.
1. Operation options
interface BaseMutationOptions
interface BaseMutationOptions< TData = any, TVariables = OperationVariables, TContext = DefaultContext, TCache extends ApolloCache<any> = ApolloCache<any>> extends MutationSharedOptions<TData, TVariables, TContext, TCache> {}
property client
client?: ApolloClient<object>;
The instance of
ApolloClient
to use to execute the mutation.By default, the instance that's passed down via context is used, but you can provide a different instance here.
2. Networking options
property ignoreResults
ignoreResults?: boolean;
If
true
:- The initial state update (setting loading to true) is skipped - The success state update (setting data and setting loading to false) is skipped - Error updates will still occur
The default value is
false
.This option is useful when you want to execute a mutation but don't need to track its progress or result in the UI, potentially improving performance by reducing re-renders.
1. Operation options
Deprecated
This option will be removed in the next major version of Apollo Client. If you don't want to synchronize your component state with the mutation, please use
useApolloClient
to get your ApolloClient instance and callclient.mutate
directly.
property notifyOnNetworkStatusChange
notifyOnNetworkStatusChange?: boolean;
If
true
, the in-progress mutation's associated component re-renders whenever the network status changes or a network error occurs.The default value is
false
.2. Networking options
property onCompleted
onCompleted?: ( data: MaybeMasked<TData>, clientOptions?: BaseMutationOptions) => void;
A callback function that's called when your mutation successfully completes with zero errors (or if
errorPolicy
isignore
and partial data is returned).This function is passed the mutation's result
data
and any options passed to the mutation.1. Operation options
property onError
onError?: (error: ApolloError, clientOptions?: BaseMutationOptions) => void;
A callback function that's called when the mutation encounters one or more errors (unless
errorPolicy
isignore
).This function is passed an [
ApolloError
](https://github.com/apollographql/apollo-client/blob/d96f4578f89b933c281bb775a39503f6cdb59ee8/src/errors/index.ts#L36-L39) object that contains either anetworkError
object or agraphQLErrors
array, depending on the error(s) that occurred, as well as any options passed the mutation.1. Operation options
interface BaseQueryOptions
interface BaseQueryOptions< TVariables extends OperationVariables = OperationVariables, TData = any> extends SharedWatchQueryOptions<TVariables, TData> {}
property client
client?: ApolloClient<any>;
The instance of
ApolloClient
to use to execute the query.By default, the instance that's passed down via context is used, but you can provide a different instance here.
1. Operation options
property context
context?: DefaultContext;
If you're using [Apollo Link](https://www.apollographql.com/docs/react/api/link/introduction/), this object is the initial value of the
context
object that's passed along your link chain.2. Networking options
property ssr
ssr?: boolean;
Pass
false
to skip executing the query during [server-side rendering](https://www.apollographql.com/docs/react/performance/server-side-rendering/).2. Networking options
interface BaseSubscriptionOptions
interface BaseSubscriptionOptions< TData = any, TVariables extends OperationVariables = OperationVariables> {}
property client
client?: ApolloClient<object>;
An
ApolloClient
instance. By defaultuseSubscription
/Subscription
uses the client passed down via context, but a different client can be passed in.
property context
context?: DefaultContext;
Shared context between your component and your network interface (Apollo Link).
property errorPolicy
errorPolicy?: ErrorPolicy;
Specifies the
ErrorPolicy
to be used for this operation
property extensions
extensions?: Record<string, any>;
Shared context between your component and your network interface (Apollo Link).
property fetchPolicy
fetchPolicy?: FetchPolicy;
How you want your component to interact with the Apollo cache. For details, see [Setting a fetch policy](https://www.apollographql.com/docs/react/data/queries/#setting-a-fetch-policy).
property ignoreResults
ignoreResults?: boolean;
If
true
, the hook will not cause the component to rerender. This is useful when you want to control the rendering of your component yourself with logic in theonData
andonError
callbacks.Changing this to
true
when the hook already hasdata
will reset thedata
toundefined
.
property onComplete
onComplete?: () => void;
Allows the registration of a callback function that will be triggered each time the
useSubscription
Hook /Subscription
component completes the subscription.3.7.0
property onData
onData?: (options: OnDataOptions<TData>) => any;
Allows the registration of a callback function that will be triggered each time the
useSubscription
Hook /Subscription
component receives data. The callbackoptions
object param consists of the current Apollo Client instance inclient
, and the received subscription data indata
.3.7.0
property onError
onError?: (error: ApolloError) => void;
Allows the registration of a callback function that will be triggered each time the
useSubscription
Hook /Subscription
component receives an error.3.7.0
property onSubscriptionComplete
onSubscriptionComplete?: () => void;
Allows the registration of a callback function that will be triggered when the
useSubscription
Hook /Subscription
component completes the subscription.Deprecated
Use
onComplete
instead
property onSubscriptionData
onSubscriptionData?: (options: OnSubscriptionDataOptions<TData>) => any;
Allows the registration of a callback function that will be triggered each time the
useSubscription
Hook /Subscription
component receives data. The callbackoptions
object param consists of the current Apollo Client instance inclient
, and the received subscription data insubscriptionData
.Deprecated
Use
onData
instead
property shouldResubscribe
shouldResubscribe?: | boolean | ((options: BaseSubscriptionOptions<TData, TVariables>) => boolean);
Determines if your subscription should be unsubscribed and subscribed again when an input to the hook (such as
subscription
orvariables
) changes.
property skip
skip?: boolean;
Determines if the current subscription should be skipped. Useful if, for example, variables depend on previous queries and are not ready yet.
property variables
variables?: TVariables;
An object containing all of the variables your subscription needs to execute
interface Context
interface DefaultContext extends Record<string, any> {}
interface DataMasking
interface DataMasking {}
interface DataProxy
interface DataProxy {}
A proxy to the normalized data living in our store. This interface allows a user to read and write denormalized data which feels natural to the user whilst in the background this data is being converted into the normalized store format.
method readFragment
readFragment: <FragmentType, TVariables = any>( options: DataProxy.ReadFragmentOptions<FragmentType, TVariables>, optimistic?: boolean) => Unmasked<FragmentType> | null;
Reads a GraphQL fragment from any arbitrary id. If there is more than one fragment in the provided document then a
fragmentName
must be provided to select the correct fragment.
method readQuery
readQuery: <QueryType, TVariables = any>( options: DataProxy.ReadQueryOptions<QueryType, TVariables>, optimistic?: boolean) => Unmasked<QueryType> | null;
Reads a GraphQL query from the root query id.
method writeFragment
writeFragment: <TData = any, TVariables = any>( options: DataProxy.WriteFragmentOptions<TData, TVariables>) => Reference | undefined;
Writes a GraphQL fragment to any arbitrary id. If there is more than one fragment in the provided document then a
fragmentName
must be provided to select the correct fragment.
method writeQuery
writeQuery: <TData = any, TVariables = any>( options: DataProxy.WriteQueryOptions<TData, TVariables>) => Reference | undefined;
Writes a GraphQL query to the root query id.
interface DefaultContext
interface DefaultContext extends Record<string, any> {}
interface DefaultOptions
interface DefaultOptions {}
property mutate
mutate?: Partial<MutationOptions<any, any, any>>;
property query
query?: Partial<QueryOptions<any, any>>;
property watchQuery
watchQuery?: Partial<WatchQueryOptions<any, any>>;
interface DefaultOptions
interface DefaultOptions {}
property react
react?: { suspense?: Readonly<SuspenseCacheOptions>;};
interface ExecutionPatchIncrementalResult
interface ExecutionPatchIncrementalResult< TData = Record<string, any>, TExtensions = Record<string, any>> extends ExecutionPatchResultBase {}
property data
data?: never;
property errors
errors?: never;
property extensions
extensions?: never;
property incremental
incremental?: IncrementalPayload<TData, TExtensions>[];
interface ExecutionPatchInitialResult
interface ExecutionPatchInitialResult< TData = Record<string, any>, TExtensions = Record<string, any>> extends ExecutionPatchResultBase {}
property data
data: TData | null | undefined;
property errors
errors?: ReadonlyArray<GraphQLFormattedError>;
property extensions
extensions?: TExtensions;
property incremental
incremental?: never;
interface FetchMoreOptions
interface FetchMoreOptions<TData = any, TVariables = OperationVariables> {}
property updateQuery
updateQuery?: ( previousQueryResult: TData, options: { fetchMoreResult?: TData; variables?: TVariables; }) => TData;
interface FetchMoreQueryOptions
interface FetchMoreQueryOptions<TVariables, TData = any> {}
property context
context?: DefaultContext;
property query
query?: DocumentNode | TypedDocumentNode<TData, TVariables>;
A GraphQL query string parsed into an AST with the gql template literal.
1. Operation options
property variables
variables?: Partial<TVariables>;
An object containing all of the GraphQL variables your query requires to execute.
Each key in the object corresponds to a variable name, and that key's value corresponds to the variable value.
1. Operation options
interface FieldFunctionOptions
interface FieldFunctionOptions< TArgs = Record<string, any>, TVars = Record<string, any>> {}
property args
args: TArgs | null;
property cache
cache: InMemoryCache;
property canRead
canRead: CanReadFunction;
property field
field: FieldNode | null;
property fieldName
fieldName: string;
property isReference
isReference: typeof isReference;
property mergeObjects
mergeObjects: MergeObjectsFunction;
property readField
readField: ReadFieldFunction;
property storage
storage: StorageType;
property storeFieldName
storeFieldName: string;
property toReference
toReference: ToReferenceFunction;
property variables
variables?: TVars;
interface GraphQLRequest
interface GraphQLRequest<TVariables = Record<string, any>> {}
property context
context?: DefaultContext;
property extensions
extensions?: Record<string, any>;
property operationName
operationName?: string;
property query
query: DocumentNode;
property variables
variables?: TVariables;
interface HttpOptions
interface HttpOptions {}
property credentials
credentials?: string;
The credentials policy you want to use for the fetch call.
property fetch
fetch?: typeof fetch;
A
fetch
-compatible API to use when making requests.
property fetchOptions
fetchOptions?: any;
Any overrides of the fetch options argument to pass to the fetch call.
property headers
headers?: Record<string, string>;
An object representing values to be sent as headers on the request.
property includeExtensions
includeExtensions?: boolean;
Passes the extensions field to your graphql server.
Defaults to false.
property includeUnusedVariables
includeUnusedVariables?: boolean;
If set to true, the default behavior of stripping unused variables from the request will be disabled.
Unused variables are likely to trigger server-side validation errors, per https://spec.graphql.org/draft/#sec-All-Variables-Used, but this includeUnusedVariables option can be useful if your server deviates from the GraphQL specification by not strictly enforcing that rule.
property preserveHeaderCase
preserveHeaderCase?: boolean;
If set to true, header names won't be automatically normalized to lowercase. This allows for non-http-spec-compliant servers that might expect capitalized header names.
property print
print?: Printer;
A function to substitute for the default query print function. Can be used to apply changes to the results of the print function.
property uri
uri?: string | UriFunction;
The URI to use when fetching operations.
Defaults to '/graphql'.
property useGETForQueries
useGETForQueries?: boolean;
If set to true, use the HTTP GET method for query operations. Mutations will still use the method specified in fetchOptions.method (which defaults to POST).
interface IdGetterObj
interface IdGetterObj extends Object {}
property id
id?: string;
interface IDocumentDefinition
interface IDocumentDefinition {}
interface IncrementalPayload
interface IncrementalPayload<TData, TExtensions> {}
property data
data: TData | null;
property errors
errors?: ReadonlyArray<GraphQLFormattedError>;
property extensions
extensions?: TExtensions;
property label
label?: string;
property path
path: Path;
interface InMemoryCacheConfig
interface InMemoryCacheConfig extends ApolloReducerConfig {}
property canonizeResults
canonizeResults?: boolean;
Deprecated
Using
canonizeResults
can result in memory leaks so we generally do not recommend using this option anymore. A future version of Apollo Client will contain a similar feature.
property fragments
fragments?: FragmentRegistryAPI;
property possibleTypes
possibleTypes?: PossibleTypesMap;
property resultCacheMaxSize
resultCacheMaxSize?: number;
Deprecated
Please use
cacheSizes
instead.
property resultCaching
resultCaching?: boolean;
property typePolicies
typePolicies?: TypePolicies;
interface InternalRefetchQueriesOptions
interface InternalRefetchQueriesOptions<TCache extends ApolloCache<any>, TResult> extends Omit<RefetchQueriesOptions<TCache, TResult>, 'include'> {}
property include
include?: InternalRefetchQueriesInclude;
property removeOptimistic
removeOptimistic?: string;
interface LazyQueryHookExecOptions
interface LazyQueryHookExecOptions< TData = any, TVariables extends OperationVariables = OperationVariables> extends LazyQueryHookOptions<TData, TVariables> {}
property query
query?: DocumentNode | TypedDocumentNode<TData, TVariables>;
interface LazyQueryHookOptions
interface LazyQueryHookOptions< TData = any, TVariables extends OperationVariables = OperationVariables> extends BaseQueryOptions<TVariables, TData> {}
property onCompleted
onCompleted?: (data: MaybeMasked<TData>) => void;
A callback function that's called when your query successfully completes with zero errors (or if
errorPolicy
isignore
and partial data is returned).This function is passed the query's result
data
.1. Operation options
Deprecated
This option will be removed in the next major version of Apollo Client. For more context, please see the [related issue](https://github.com/apollographql/apollo-client/issues/12352) on GitHub.
property onError
onError?: (error: ApolloError) => void;
A callback function that's called when the query encounters one or more errors (unless
errorPolicy
isignore
).This function is passed an
ApolloError
object that contains either anetworkError
object or agraphQLErrors
array, depending on the error(s) that occurred.1. Operation options
Deprecated
This option will be removed in the next major version of Apollo Client. For more context, please see the [related issue](https://github.com/apollographql/apollo-client/issues/12352) on GitHub.
interface LoadableQueryHookOptions
interface LoadableQueryHookOptions {}
property canonizeResults
canonizeResults?: 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.
Deprecated
Using
canonizeResults
can result in memory leaks so we generally do not recommend using this option anymore. A future version of Apollo Client will contain a similar feature without the risk of memory leaks.
property client
client?: ApolloClient<any>;
The instance of
ApolloClient
to use to execute the query.By default, the instance that's passed down via context is used, but you can provide a different instance here.
1. Operation options
property context
context?: DefaultContext;
If you're using [Apollo Link](https://www.apollographql.com/docs/react/api/link/introduction/), this object is the initial value of the
context
object that's passed along your link chain.2. Networking options
property errorPolicy
errorPolicy?: ErrorPolicy;
Specifies how the query handles a response that returns both GraphQL errors and partial results.
For details, see [GraphQL error policies](https://www.apollographql.com/docs/react/data/error-handling/#graphql-error-policies).
The default value is
none
, meaning that the query result includes error details but not partial results.1. Operation options
property fetchPolicy
fetchPolicy?: LoadableQueryHookFetchPolicy;
Specifies how the query interacts with the Apollo Client 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](https://www.apollographql.com/docs/react/data/queries/#setting-a-fetch-policy).
The default value is
cache-first
.3. Caching options
property queryKey
queryKey?: string | number | any[];
A unique identifier for the query. Each item in the array must be a stable identifier to prevent infinite fetches.
This is useful when using the same query and variables combination in more than one component, otherwise the components may clobber each other. This can also be used to force the query to re-evaluate fresh.
1. Operation options
property refetchWritePolicy
refetchWritePolicy?: RefetchWritePolicy;
Specifies whether a
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.3. Caching options
property returnPartialData
returnPartialData?: boolean;
If
true
, the query can return partial results from the cache if the cache doesn't contain results for all queried fields.The default value is
false
.3. Caching options
interface MergeInfo
interface MergeInfo {}
interface MergeTree
interface MergeTree {}
interface MutationDataOptions
interface MutationDataOptions< TData = any, TVariables = OperationVariables, TContext = DefaultContext, TCache extends ApolloCache<any> = ApolloCache<any>> extends BaseMutationOptions<TData, TVariables, TContext, TCache> {}
property mutation
mutation: DocumentNode | TypedDocumentNode<TData, TVariables>;
interface MutationFunctionOptions
interface MutationFunctionOptions< TData = any, TVariables = OperationVariables, TContext = DefaultContext, TCache extends ApolloCache<any> = ApolloCache<any>> extends BaseMutationOptions<TData, TVariables, TContext, TCache> {}
property mutation
mutation?: DocumentNode | TypedDocumentNode<TData, TVariables>;
A GraphQL document, often created with
gql
from thegraphql-tag
package, that contains a single mutation inside of it.1. Operation options
interface MutationHookOptions
interface MutationHookOptions< TData = any, TVariables = OperationVariables, TContext = DefaultContext, TCache extends ApolloCache<any> = ApolloCache<any>> extends BaseMutationOptions<TData, TVariables, TContext, TCache> {}
interface MutationOptions
interface MutationOptions< TData = any, TVariables = OperationVariables, TContext = DefaultContext, TCache extends ApolloCache<any> = ApolloCache<any>> extends MutationSharedOptions<TData, TVariables, TContext, TCache> {}
property mutation
mutation: DocumentNode | TypedDocumentNode<TData, TVariables>;
A GraphQL document, often created with
gql
from thegraphql-tag
package, that contains a single mutation inside of it.1. Operation options
interface MutationResult
interface MutationResult<TData = any> {}
property called
called: boolean;
If
true
, the mutation's mutate function has been called.
property client
client: ApolloClient<object>;
The instance of Apollo Client that executed the mutation.
Can be useful for manually executing followup operations or writing data to the cache.
property data
data?: MaybeMasked<TData> | null;
The data returned from your mutation. Can be
undefined
ifignoreResults
istrue
.
property error
error?: ApolloError;
If the mutation produces one or more errors, this object contains either an array of
graphQLErrors
or a singlenetworkError
. Otherwise, this value isundefined
.For more information, see [Handling operation errors](https://www.apollographql.com/docs/react/data/error-handling/).
property loading
loading: boolean;
If
true
, the mutation is currently in flight.
property reset
reset: () => void;
A function that you can call to reset the mutation's result to its initial, uncalled state.
interface NormalizedCache
interface NormalizedCache {}
This is an interface used to access, set and remove StoreObjects from the cache
property canRead
canRead: CanReadFunction;
property getFieldValue
getFieldValue: FieldValueGetter;
property toReference
toReference: ToReferenceFunction;
method clear
clear: () => void;
method delete
delete: (dataId: string, fieldName?: string) => boolean;
method get
get: (dataId: string, fieldName: string) => StoreValue;
method getStorage
getStorage: ( idOrObj: string | StoreObject, ...storeFieldNames: (string | number)[]) => StorageType;
method has
has: (dataId: string) => boolean;
method merge
merge: { (olderId: string, newerObject: StoreObject): void; (olderObject: StoreObject, newerId: string): void;};
method modify
modify: <Entity extends Record<string, any>>( dataId: string, fields: Modifiers<Entity> | AllFieldsModifier<Entity>) => boolean;
method release
release: (rootId: string) => number;
method replace
replace: (newData: NormalizedCacheObject) => void;
replace the state of the store
method retain
retain: (rootId: string) => number;
Retain (or release) a given root ID to protect (or expose) it and its transitive child entities from (or to) garbage collection. The current retainment count is returned by both methods. Note that releasing a root ID does not cause that entity to be garbage collected, but merely removes it from the set of root IDs that will be considered during the next mark-and-sweep collection.
method toObject
toObject: () => NormalizedCacheObject;
returns an Object with key-value pairs matching the contents of the store
interface NormalizedCacheObject
interface NormalizedCacheObject {}
This is a normalized representation of the Apollo query result cache. It consists of a flattened representation of query result trees.
index signature
[dataId: string]: StoreObject | undefined;
interface ObservableQueryFields
interface ObservableQueryFields<TData, TVariables extends OperationVariables> {}
property fetchMore
fetchMore: < TFetchData = TData, TFetchVars extends OperationVariables = TVariables>( fetchMoreOptions: FetchMoreQueryOptions<TFetchVars, TFetchData> & { updateQuery?: ( previousQueryResult: Unmasked<TData>, options: { fetchMoreResult: Unmasked<TFetchData>; variables: TFetchVars; } ) => Unmasked<TData>; }) => Promise<ApolloQueryResult<MaybeMasked<TFetchData>>>;
A function that helps you fetch the next set of results for a [paginated list field](https://www.apollographql.com/docs/react/pagination/core-api/).
3. Helper functions
property refetch
refetch: ( variables?: Partial<TVariables>) => Promise<ApolloQueryResult<MaybeMasked<TData>>>;
A function that enables you to re-execute the query, optionally passing in new
variables
.To guarantee that the refetch performs a network request, its
fetchPolicy
is set tonetwork-only
(unless the original query'sfetchPolicy
isno-cache
orcache-and-network
, which also guarantee a network request).See also [Refetching](https://www.apollographql.com/docs/react/data/queries/#refetching).
3. Helper functions
property startPolling
startPolling: (pollInterval: number) => void;
A function that instructs the query to begin re-executing at a specified interval (in milliseconds).
3. Helper functions
property stopPolling
stopPolling: () => void;
A function that instructs the query to stop polling after a previous call to
startPolling
.3. Helper functions
property subscribeToMore
subscribeToMore: SubscribeToMoreFunction<TData, TVariables>;
A function that enables you to execute a [subscription](https://www.apollographql.com/docs/react/data/subscriptions/), 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.
3. Helper functions
property updateQuery
updateQuery: (mapFn: UpdateQueryMapFn<TData, TVariables>) => void;
A function that enables you to update the query's cached result without executing a followup GraphQL operation.
See [using updateQuery and updateFragment](https://www.apollographql.com/docs/react/caching/cache-interaction/#using-updatequery-and-updatefragment) for additional information.
3. Helper functions
property variables
variables: TVariables | undefined;
An object containing the variables that were provided for the query.
1. Operation data
interface OnDataOptions
interface OnDataOptions<TData = any> {}
interface OnSubscriptionDataOptions
interface OnSubscriptionDataOptions<TData = any> {}
property client
client: ApolloClient<object>;
property subscriptionData
subscriptionData: SubscriptionResult<TData>;
interface Operation
interface Operation {}
property extensions
extensions: Record<string, any>;
property getContext
getContext: () => DefaultContext;
property operationName
operationName: string;
property query
query: DocumentNode;
property setContext
setContext: { (context: Partial<DefaultContext>): void; ( updateContext: ( previousContext: DefaultContext ) => Partial<DefaultContext> ): void;};
property variables
variables: Record<string, any>;
interface PreloadedQueryRef
interface PreloadedQueryRef<TData = unknown, TVariables = unknown> extends QueryRef<TData, TVariables> {}
A
QueryReference
is an opaque object returned byuseBackgroundQuery
. A child component reading theQueryReference
viauseReadQuery
will suspend until the promise resolves.
method toPromise
toPromise: () => Promise<PreloadedQueryRef<TData, TVariables>>;
A function that returns a promise that resolves when the query has finished loading. The promise resolves with the
QueryReference
itself.Remarks
This method is useful for preloading queries in data loading routers, such as [React Router](https://reactrouter.com/en/main) or [TanStack Router](https://tanstack.com/router), to prevent routes from transitioning until the query has finished loading.
data
is not exposed on the promise to discourage using the data inloader
functions and exposing it to your route components. Instead, we prefer you rely onuseReadQuery
to access the data to ensure your component can rerender with cache updates. If you need to access raw query data, useclient.query()
directly.Example 1
Here's an example using React Router's
loader
function:import { createQueryPreloader } from "@apollo/client";const preloadQuery = createQueryPreloader(client);export async function loader() {const queryRef = preloadQuery(GET_DOGS_QUERY);return queryRef.toPromise();}export function RouteComponent() {const queryRef = useLoaderData();const { data } = useReadQuery(queryRef);// ...}3.9.0
interface PreloadQueryFunction
interface PreloadQueryFunction {}
A function that will begin loading a query when called. It's result can be read by
useReadQuery
which will suspend until the query is loaded. This is useful when you want to start loading a query as early as possible outside of a React component.Example 1
const preloadQuery = createQueryPreloader(client);const queryRef = preloadQuery(query, { variables, ...otherOptions });function App() {return (<Suspense fallback={<div>Loading</div>}><MyQuery /></Suspense>);}function MyQuery() {const { data } = useReadQuery(queryRef);// do something with `data`}
call signature
< TData, TVariables extends OperationVariables, TOptions extends Omit<PreloadQueryOptions, 'variables'>>( query: DocumentNode | TypedDocumentNode<TData, TVariables>, ...[options]: PreloadQueryOptionsArg<NoInfer<TVariables>, TOptions>): PreloadedQueryRef< TOptions['errorPolicy'] extends 'ignore' | 'all' ? TOptions['returnPartialData'] extends true ? DeepPartial<TData> | undefined : TData | undefined : TOptions['returnPartialData'] extends true ? DeepPartial<TData> : TData, TVariables>;
A function that will begin loading a query when called. It's result can be read by
useReadQuery
which will suspend until the query is loaded. This is useful when you want to start loading a query as early as possible outside of a React component.Example 1
const preloadQuery = createQueryPreloader(client);const queryRef = preloadQuery(query, { variables, ...otherOptions });function App() {return (<Suspense fallback={<div>Loading</div>}><MyQuery /></Suspense>);}function MyQuery() {const { data } = useReadQuery(queryRef);// do something with `data`}
call signature
<TData = unknown, TVariables extends OperationVariables = OperationVariables>( query: DocumentNode | TypedDocumentNode<TData, TVariables>, options: PreloadQueryOptions<NoInfer<TVariables>> & { returnPartialData: true; errorPolicy: 'ignore' | 'all'; }): PreloadedQueryRef<DeepPartial<TData> | undefined, TVariables>;
A function that will begin loading a query when called. It's result can be read by
useReadQuery
which will suspend until the query is loaded. This is useful when you want to start loading a query as early as possible outside of a React component.Example 1
const preloadQuery = createQueryPreloader(client);const queryRef = preloadQuery(query, { variables, ...otherOptions });function App() {return (<Suspense fallback={<div>Loading</div>}><MyQuery /></Suspense>);}function MyQuery() {const { data } = useReadQuery(queryRef);// do something with `data`}
call signature
<TData = unknown, TVariables extends OperationVariables = OperationVariables>( query: DocumentNode | TypedDocumentNode<TData, TVariables>, options: PreloadQueryOptions<NoInfer<TVariables>> & { errorPolicy: 'ignore' | 'all'; }): PreloadedQueryRef<TData | undefined, TVariables>;
A function that will begin loading a query when called. It's result can be read by
useReadQuery
which will suspend until the query is loaded. This is useful when you want to start loading a query as early as possible outside of a React component.Example 1
const preloadQuery = createQueryPreloader(client);const queryRef = preloadQuery(query, { variables, ...otherOptions });function App() {return (<Suspense fallback={<div>Loading</div>}><MyQuery /></Suspense>);}function MyQuery() {const { data } = useReadQuery(queryRef);// do something with `data`}
call signature
<TData = unknown, TVariables extends OperationVariables = OperationVariables>( query: DocumentNode | TypedDocumentNode<TData, TVariables>, options: PreloadQueryOptions<NoInfer<TVariables>> & { returnPartialData: true; }): PreloadedQueryRef<DeepPartial<TData>, TVariables>;
A function that will begin loading a query when called. It's result can be read by
useReadQuery
which will suspend until the query is loaded. This is useful when you want to start loading a query as early as possible outside of a React component.Example 1
const preloadQuery = createQueryPreloader(client);const queryRef = preloadQuery(query, { variables, ...otherOptions });function App() {return (<Suspense fallback={<div>Loading</div>}><MyQuery /></Suspense>);}function MyQuery() {const { data } = useReadQuery(queryRef);// do something with `data`}
call signature
<TData = unknown, TVariables extends OperationVariables = OperationVariables>( query: DocumentNode | TypedDocumentNode<TData, TVariables>, ...[options]: PreloadQueryOptionsArg<NoInfer<TVariables>>): PreloadedQueryRef<TData, TVariables>;
A function that will begin loading a query when called. It's result can be read by
useReadQuery
which will suspend until the query is loaded. This is useful when you want to start loading a query as early as possible outside of a React component.Example 1
const preloadQuery = createQueryPreloader(client);const queryRef = preloadQuery(query, { variables, ...otherOptions });function App() {return (<Suspense fallback={<div>Loading</div>}><MyQuery /></Suspense>);}function MyQuery() {const { data } = useReadQuery(queryRef);// do something with `data`}
interface PureQueryOptions
interface QueryOptions<TVariables = OperationVariables, TData = any> {}
Query options.
property canonizeResults
canonizeResults?: 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.
Deprecated
Using
canonizeResults
can result in memory leaks so we generally do not recommend using this option anymore. A future version of Apollo Client will contain a similar feature without the risk of memory leaks.
property context
context?: DefaultContext;
If you're using [Apollo Link](https://www.apollographql.com/docs/react/api/link/introduction/), this object is the initial value of the
context
object that's passed along your link chain.2. Networking options
property errorPolicy
errorPolicy?: ErrorPolicy;
Specifies how the query handles a response that returns both GraphQL errors and partial results.
For details, see [GraphQL error policies](https://www.apollographql.com/docs/react/data/error-handling/#graphql-error-policies).
The default value is
none
, meaning that the query result includes error details but not partial results.1. Operation options
property fetchPolicy
fetchPolicy?: FetchPolicy;
Specifies how the query interacts with the Apollo Client 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](https://www.apollographql.com/docs/react/data/queries/#setting-a-fetch-policy).
The default value is
cache-first
.3. Caching options
property notifyOnNetworkStatusChange
notifyOnNetworkStatusChange?: boolean;
If
true
, the in-progress query's associated component re-renders whenever the network status changes or a network error occurs.The default value is
false
.2. Networking options
property partialRefetch
partialRefetch?: boolean;
If
true
, causes a query refetch if the query result is detected as partial.The default value is
false
.Deprecated
Setting this option is unnecessary in Apollo Client 3, thanks to a more consistent application of fetch policies. It might be removed in a future release.
property pollInterval
pollInterval?: number;
Specifies the interval (in milliseconds) at which the query polls for updated results.
The default value is
0
(no polling).2. Networking options
property query
query: DocumentNode | TypedDocumentNode<TData, TVariables>;
A GraphQL query string parsed into an AST with the gql template literal.
1. Operation options
property returnPartialData
returnPartialData?: boolean;
If
true
, the query can return partial results from the cache if the cache doesn't contain results for all queried fields.The default value is
false
.3. Caching options
property variables
variables?: TVariables;
An object containing all of the GraphQL variables your query requires to execute.
Each key in the object corresponds to a variable name, and that key's value corresponds to the variable value.
1. Operation options
interface QueryDataOptions
interface QueryDataOptions< TData = any, TVariables extends OperationVariables = OperationVariables> extends QueryFunctionOptions<TData, TVariables> {}
interface QueryFunctionOptions
interface QueryFunctionOptions< TData = any, TVariables extends OperationVariables = OperationVariables> extends BaseQueryOptions<TVariables, TData> {}
property onCompleted
onCompleted?: (data: MaybeMasked<TData>) => void;
A callback function that's called when your query successfully completes with zero errors (or if
errorPolicy
isignore
and partial data is returned).This function is passed the query's result
data
.1. Operation options
Deprecated
This option will be removed in the next major version of Apollo Client. For more context, please see the [related issue](https://github.com/apollographql/apollo-client/issues/12352) on GitHub.
property onError
onError?: (error: ApolloError) => void;
A callback function that's called when the query encounters one or more errors (unless
errorPolicy
isignore
).This function is passed an
ApolloError
object that contains either anetworkError
object or agraphQLErrors
array, depending on the error(s) that occurred.1. Operation options
Deprecated
This option will be removed in the next major version of Apollo Client. For more context, please see the [related issue](https://github.com/apollographql/apollo-client/issues/12352) on GitHub.
property skip
skip?: boolean;
If true, the query is not executed.
The default value is
false
.1. Operation options
interface QueryHookOptions
interface QueryHookOptions< TData = any, TVariables extends OperationVariables = OperationVariables> extends QueryFunctionOptions<TData, TVariables> {}
interface QueryLazyOptions
interface QueryLazyOptions<TVariables> {}
Deprecated
This type will be removed in the next major version of Apollo Client
property context
context?: DefaultContext;
If you're using [Apollo Link](https://www.apollographql.com/docs/react/api/link/introduction/), this object is the initial value of the
context
object that's passed along your link chain.2. Networking options
property variables
variables?: TVariables;
An object containing all of the GraphQL variables your query requires to execute.
Each key in the object corresponds to a variable name, and that key's value corresponds to the variable value.
1. Operation options
interface QueryOptions
interface QueryOptions<TVariables = OperationVariables, TData = any> {}
Query options.
property canonizeResults
canonizeResults?: 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.
Deprecated
Using
canonizeResults
can result in memory leaks so we generally do not recommend using this option anymore. A future version of Apollo Client will contain a similar feature without the risk of memory leaks.
property context
context?: DefaultContext;
If you're using [Apollo Link](https://www.apollographql.com/docs/react/api/link/introduction/), this object is the initial value of the
context
object that's passed along your link chain.2. Networking options
property errorPolicy
errorPolicy?: ErrorPolicy;
Specifies how the query handles a response that returns both GraphQL errors and partial results.
For details, see [GraphQL error policies](https://www.apollographql.com/docs/react/data/error-handling/#graphql-error-policies).
The default value is
none
, meaning that the query result includes error details but not partial results.1. Operation options
property fetchPolicy
fetchPolicy?: FetchPolicy;
Specifies how the query interacts with the Apollo Client 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](https://www.apollographql.com/docs/react/data/queries/#setting-a-fetch-policy).
The default value is
cache-first
.3. Caching options
property notifyOnNetworkStatusChange
notifyOnNetworkStatusChange?: boolean;
If
true
, the in-progress query's associated component re-renders whenever the network status changes or a network error occurs.The default value is
false
.2. Networking options
property partialRefetch
partialRefetch?: boolean;
If
true
, causes a query refetch if the query result is detected as partial.The default value is
false
.Deprecated
Setting this option is unnecessary in Apollo Client 3, thanks to a more consistent application of fetch policies. It might be removed in a future release.
property pollInterval
pollInterval?: number;
Specifies the interval (in milliseconds) at which the query polls for updated results.
The default value is
0
(no polling).2. Networking options
property query
query: DocumentNode | TypedDocumentNode<TData, TVariables>;
A GraphQL query string parsed into an AST with the gql template literal.
1. Operation options
property returnPartialData
returnPartialData?: boolean;
If
true
, the query can return partial results from the cache if the cache doesn't contain results for all queried fields.The default value is
false
.3. Caching options
property variables
variables?: TVariables;
An object containing all of the GraphQL variables your query requires to execute.
Each key in the object corresponds to a variable name, and that key's value corresponds to the variable value.
1. Operation options
interface QueryRef
interface QueryRef<TData = unknown, TVariables = unknown> {}
A
QueryReference
is an opaque object returned byuseBackgroundQuery
. A child component reading theQueryReference
viauseReadQuery
will suspend until the promise resolves.
interface QueryReference
interface QueryReference<TData = unknown, TVariables = unknown> extends QueryRef<TData, TVariables> {}
Deprecated
Please use the
QueryRef
interface instead ofQueryReference
.A
QueryReference
is an opaque object returned byuseBackgroundQuery
. A child component reading theQueryReference
viauseReadQuery
will suspend until the promise resolves.
property toPromise
toPromise?: unknown;
Remarks
This method is useful for preloading queries in data loading routers, such as [React Router](https://reactrouter.com/en/main) or [TanStack Router](https://tanstack.com/router), to prevent routes from transitioning until the query has finished loading.
data
is not exposed on the promise to discourage using the data inloader
functions and exposing it to your route components. Instead, we prefer you rely onuseReadQuery
to access the data to ensure your component can rerender with cache updates. If you need to access raw query data, useclient.query()
directly.Example 1
Here's an example using React Router's
loader
function:import { createQueryPreloader } from "@apollo/client";const preloadQuery = createQueryPreloader(client);export async function loader() {const queryRef = preloadQuery(GET_DOGS_QUERY);return queryRef.toPromise();}export function RouteComponent() {const queryRef = useLoaderData();const { data } = useReadQuery(queryRef);// ...}3.9.0
Deprecated
Please use the
QueryRef
interface instead ofQueryReference
.A function that returns a promise that resolves when the query has finished loading. The promise resolves with the
QueryReference
itself.
interface QueryResult
interface QueryResult< TData = any, TVariables extends OperationVariables = OperationVariables> extends ObservableQueryFields<TData, TVariables> {}
property called
called: boolean;
If
true
, the associated lazy query has been executed.This field is only present on the result object returned by [
useLazyQuery
](/react/data/queries/#executing-queries-manually).2. Network info
property client
client: ApolloClient<any>;
The instance of Apollo Client that executed the query. Can be useful for manually executing followup queries or writing data to the cache.
2. Network info
property data
data: 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'serrorPolicy
).1. Operation data
property error
error?: ApolloError;
If the query produces one or more errors, this object contains either an array of
graphQLErrors
or a singlenetworkError
. Otherwise, this value isundefined
.For more information, see [Handling operation errors](https://www.apollographql.com/docs/react/data/error-handling/).
1. Operation data
property errors
errors?: ReadonlyArray<GraphQLFormattedError>;
Deprecated
This property will be removed in a future version of Apollo Client. Please use
error.graphQLErrors
instead.
property loading
loading: boolean;
If
true
, the query is still in flight and results have not yet been returned.2. Network info
property networkStatus
networkStatus: NetworkStatus;
A number indicating the current network state of the query's associated request. [See possible values.](https://github.com/apollographql/apollo-client/blob/d96f4578f89b933c281bb775a39503f6cdb59ee8/src/core/networkStatus.ts#L4)
Used in conjunction with the [
notifyOnNetworkStatusChange
](#notifyonnetworkstatuschange) option.2. Network info
property observable
observable: ObservableQuery<TData, TVariables>;
A reference to the internal
ObservableQuery
used by the hook.
property previousData
previousData?: MaybeMasked<TData>;
An object containing the result from the most recent _previous_ execution of this query.
This value is
undefined
if this is the query's first execution.1. Operation data
interface ReactiveVar
interface ReactiveVar<T> {}
method attachCache
attachCache: (cache: ApolloCache<any>) => this;
method forgetCache
forgetCache: (cache: ApolloCache<any>) => boolean;
method onNextChange
onNextChange: (listener: ReactiveListener<T>) => () => void;
call signature
(newValue?: T): T;
interface ReadMergeModifyContext
interface ReadMergeModifyContext {}
interface Reference
interface Reference {}
interface RefetchQueriesOptions
interface RefetchQueriesOptions<TCache extends ApolloCache<any>, TResult> {}
property include
include?: RefetchQueriesInclude;
property onQueryUpdated
onQueryUpdated?: OnQueryUpdated<TResult> | null;
property optimistic
optimistic?: boolean;
property updateCache
updateCache?: (cache: TCache) => void;
interface RefetchQueriesResult
interface RefetchQueriesResult<TResult> extends Promise<RefetchQueriesPromiseResults<TResult>> {}
interface Resolvers
interface Resolvers {}
index signature
[key: string]: { [field: string]: Resolver;};
interface SingleExecutionResult
interface SingleExecutionResult< TData = Record<string, any>, TContext = DefaultContext, TExtensions = Record<string, any>> {}
property context
context?: TContext;
property data
data?: TData | null;
property errors
errors?: ReadonlyArray<GraphQLFormattedError>;
property extensions
extensions?: TExtensions;
interface StoreObject
interface StoreObject {}
index signature
[storeFieldName: string]: StoreValue;
interface SubscribeToMoreFunction
interface SubscribeToMoreFunction< TData, TVariables extends OperationVariables = OperationVariables> {}
call signature
< TSubscriptionData = TData, TSubscriptionVariables extends OperationVariables = TVariables>( options: SubscribeToMoreOptions< TData, TSubscriptionVariables, TSubscriptionData, TVariables >): () => void;
interface SubscribeToMoreOptions
interface SubscribeToMoreOptions< TData = any, TSubscriptionVariables extends OperationVariables = OperationVariables, TSubscriptionData = TData, TVariables extends OperationVariables = TSubscriptionVariables> {}
property context
context?: DefaultContext;
property document
document: | DocumentNode | TypedDocumentNode<TSubscriptionData, TSubscriptionVariables>;
property onError
onError?: (error: Error) => void;
property updateQuery
updateQuery?: SubscribeToMoreUpdateQueryFn<TData, TVariables, TSubscriptionData>;
property variables
variables?: TSubscriptionVariables;
interface SubscriptionCurrentObservable
interface SubscriptionCurrentObservable {}
property query
query?: Observable<any>;
property subscription
subscription?: ObservableSubscription;
interface SubscriptionDataOptions
interface SubscriptionDataOptions< TData = any, TVariables extends OperationVariables = OperationVariables> extends BaseSubscriptionOptions<TData, TVariables> {}
Deprecated
This type is not used anymore. It will be removed in the next major version of Apollo Client
property children
children?: null | ((result: SubscriptionResult<TData>) => ReactTypes.ReactNode);
property subscription
subscription: DocumentNode | TypedDocumentNode<TData, TVariables>;
interface SubscriptionHookOptions
interface SubscriptionHookOptions< TData = any, TVariables extends OperationVariables = OperationVariables> extends BaseSubscriptionOptions<TData, TVariables> {}
interface SubscriptionOptions
interface SubscriptionOptions<TVariables = OperationVariables, TData = any> {}
property context
context?: DefaultContext;
Shared context between your component and your network interface (Apollo Link).
property errorPolicy
errorPolicy?: ErrorPolicy;
Specifies the
ErrorPolicy
to be used for this operation
property extensions
extensions?: Record<string, any>;
Shared context between your component and your network interface (Apollo Link).
property fetchPolicy
fetchPolicy?: FetchPolicy;
How you want your component to interact with the Apollo cache. For details, see [Setting a fetch policy](https://www.apollographql.com/docs/react/data/queries/#setting-a-fetch-policy).
property query
query: DocumentNode | TypedDocumentNode<TData, TVariables>;
A GraphQL document, often created with
gql
from thegraphql-tag
package, that contains a single subscription inside of it.
property variables
variables?: TVariables;
An object containing all of the variables your subscription needs to execute
interface SubscriptionResult
interface SubscriptionResult<TData = any, TVariables = any> {}
property data
data?: MaybeMasked<TData>;
An object containing the result of your GraphQL subscription. Defaults to an empty object.
property error
error?: ApolloError;
A runtime error with
graphQLErrors
andnetworkError
properties
property loading
loading: boolean;
A boolean that indicates whether any initial data has been returned
interface SuspenseQueryHookOptions
interface SuspenseQueryHookOptions< TData = unknown, TVariables extends OperationVariables = OperationVariables> {}
property canonizeResults
canonizeResults?: 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.
Deprecated
Using
canonizeResults
can result in memory leaks so we generally do not recommend using this option anymore. A future version of Apollo Client will contain a similar feature without the risk of memory leaks.
property client
client?: ApolloClient<any>;
The instance of
ApolloClient
to use to execute the query.By default, the instance that's passed down via context is used, but you can provide a different instance here.
1. Operation options
property context
context?: DefaultContext;
If you're using [Apollo Link](https://www.apollographql.com/docs/react/api/link/introduction/), this object is the initial value of the
context
object that's passed along your link chain.2. Networking options
property errorPolicy
errorPolicy?: ErrorPolicy;
Specifies how the query handles a response that returns both GraphQL errors and partial results.
For details, see [GraphQL error policies](https://www.apollographql.com/docs/react/data/error-handling/#graphql-error-policies).
The default value is
none
, meaning that the query result includes error details but not partial results.1. Operation options
property fetchPolicy
fetchPolicy?: SuspenseQueryHookFetchPolicy;
Specifies how the query interacts with the Apollo Client 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](https://www.apollographql.com/docs/react/data/queries/#setting-a-fetch-policy).
The default value is
cache-first
.3. Caching options
property queryKey
queryKey?: string | number | any[];
A unique identifier for the query. Each item in the array must be a stable identifier to prevent infinite fetches.
This is useful when using the same query and variables combination in more than one component, otherwise the components may clobber each other. This can also be used to force the query to re-evaluate fresh.
1. Operation options
property refetchWritePolicy
refetchWritePolicy?: RefetchWritePolicy;
Watched queries must opt into overwriting existing data on refetch, by passing refetchWritePolicy: "overwrite" in their WatchQueryOptions.
The default value is "overwrite".
3. Caching options
property returnPartialData
returnPartialData?: boolean;
If
true
, the query can return partial results from the cache if the cache doesn't contain results for all queried fields.The default value is
false
.3. Caching options
property skip
skip?: boolean;
If
true
, the query is not executed. The default value isfalse
.Example 1
Recommended usage of
skipToken
:import { skipToken, useSuspenseQuery } from '@apollo/client';const { data } = useSuspenseQuery(query, id ? { variables: { id } } : skipToken);Deprecated
We recommend using
skipToken
in place of theskip
option as it is more type-safe.This option is deprecated and only supported to ease the migration from useQuery. It will be removed in a future release.
1. Operation options
property variables
variables?: TVariables;
An object containing all of the GraphQL variables your query requires to execute.
Each key in the object corresponds to a variable name, and that key's value corresponds to the variable value.
1. Operation options
interface UpdateQueryMapFn
interface UpdateQueryMapFn<TData = any, TVariables = OperationVariables> {}
call signature
( /** * @deprecated This value is not type-safe and may contain partial data. This * argument will be removed in the next major version of Apollo Client. Use * `options.previousData` instead for a more type-safe value. */ unsafePreviousData: Unmasked<TData>, options: UpdateQueryOptions<TData, TVariables>): Unmasked<TData> | void;
interface UriFunction
interface UriFunction {}
call signature
(operation: Operation): string;
interface UseFragmentOptions
interface UseFragmentOptions<TData, TVars> extends Omit< Cache.DiffOptions<NoInfer<TData>, NoInfer<TVars>>, 'id' | 'query' | 'optimistic' | 'previousResult' | 'returnPartialData' >, Omit< Cache.ReadFragmentOptions<TData, TVars>, 'id' | 'variables' | 'returnPartialData' > {}
property client
client?: ApolloClient<any>;
The instance of
ApolloClient
to use to look up the fragment.By default, the instance that's passed down via context is used, but you can provide a different instance here.
1. Operation options
property from
from: StoreObject | Reference | FragmentType<NoInfer<TData>> | string | null;
property optimistic
optimistic?: boolean;
interface UseQueryRefHandlersResult
interface UseQueryRefHandlersResult< TData = unknown, TVariables extends OperationVariables = OperationVariables> {}
property fetchMore
fetchMore: FetchMoreFunction<TData, TVariables>;
A function that helps you fetch the next set of results for a [paginated list field](https://www.apollographql.com/docs/react/pagination/core-api/).
property refetch
refetch: RefetchFunction<TData, TVariables>;
Update the variables of this observable query, and fetch the new results. This method should be preferred over
setVariables
in most use cases.Parameter variables
The new set of variables. If there are missing variables, the previous values of those variables will be used.
property subscribeToMore
subscribeToMore: SubscribeToMoreFunction<TData, TVariables>;
A function that enables you to execute a [subscription](https://www.apollographql.com/docs/react/data/subscriptions/), 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.
interface UseReadQueryResult
interface UseReadQueryResult<TData = unknown> {}
property data
data: MaybeMasked<TData>;
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'serrorPolicy
).
property error
error: ApolloError | undefined;
If the query produces one or more errors, this object contains either an array of
graphQLErrors
or a singlenetworkError
. Otherwise, this value isundefined
.This property can be ignored when using the default
errorPolicy
or anerrorPolicy
ofnone
. The hook will throw the error instead of setting this property.
property networkStatus
networkStatus: NetworkStatus;
A number indicating the current network state of the query's associated request. See possible values.
interface UseSuspenseQueryResult
interface UseSuspenseQueryResult< TData = unknown, TVariables extends OperationVariables = OperationVariables> {}
property client
client: ApolloClient<any>;
property data
data: MaybeMasked<TData>;
property error
error: ApolloError | undefined;
property fetchMore
fetchMore: FetchMoreFunction<TData, TVariables>;
property networkStatus
networkStatus: NetworkStatus;
property refetch
refetch: RefetchFunction<TData, TVariables>;
property subscribeToMore
subscribeToMore: SubscribeToMoreFunction<TData, TVariables>;
interface WatchFragmentOptions
interface WatchFragmentOptions<TData, TVars> {}
Watched fragment options.
property fragment
fragment: DocumentNode | TypedDocumentNode<TData, TVars>;
A GraphQL fragment document parsed into an AST with the
gql
template literal.1. Required options
property fragmentName
fragmentName?: string;
The name of the fragment defined in the fragment document.
Required if the fragment document includes more than one fragment, optional otherwise.
2. Cache options
property from
from: StoreObject | Reference | FragmentType<NoInfer<TData>> | string;
An object containing a
__typename
and primary key fields (such asid
) identifying the entity object from which the fragment will be retrieved, or a{ __ref: "..." }
reference, or astring
ID (uncommon).1. Required options
property optimistic
optimistic?: boolean;
If
true
,watchFragment
returns optimistic results.The default value is
true
.2. Cache options
property variables
variables?: TVars;
Any variables that the GraphQL fragment may depend on.
2. Cache options
interface WatchQueryOptions
interface WatchQueryOptions< TVariables extends OperationVariables = OperationVariables, TData = any> extends SharedWatchQueryOptions<TVariables, TData> {}
Watched query options.
property query
query: DocumentNode | TypedDocumentNode<TData, TVariables>;
A GraphQL query string parsed into an AST with the gql template literal.
1. Operation options
Enums
enum DocumentType
enum DocumentType { Query = 0, Mutation = 1, Subscription = 2,}
enum NetworkStatus
enum NetworkStatus { loading = 1, setVariables = 2, fetchMore = 3, refetch = 4, poll = 6, ready = 7, error = 8,}
The current status of a query’s execution in our system.
member error
error = 8
No request is in flight for this query, but one or more errors were detected.
member fetchMore
fetchMore = 3
Indicates that
fetchMore
was called on this query and that the query created is currently in flight.
member loading
loading = 1
The query has never been run before and the query is now currently running. A query will still have this network status even if a partial data result was returned from the cache, but a query was dispatched anyway.
member poll
poll = 6
Indicates that a polling query is currently in flight. So for example if you are polling a query every 10 seconds then the network status will switch to
poll
every 10 seconds whenever a poll request has been sent but not resolved.
member ready
ready = 7
No request is in flight for this query, and no errors happened. Everything is OK.
member refetch
refetch = 4
Similar to the
setVariables
network status. It means thatrefetch
was called on a query and the refetch request is currently in flight.
member setVariables
setVariables = 2
If
setVariables
was called and a query was fired because of that then the network status will besetVariables
until the result of that query comes back.
Type Aliases
type ApolloReducerConfig
type ApolloReducerConfig = { dataIdFromObject?: KeyFieldsFunction; addTypename?: boolean;};
type BackgroundQueryHookFetchPolicy
type BackgroundQueryHookFetchPolicy = Extract< WatchQueryFetchPolicy, 'cache-first' | 'network-only' | 'no-cache' | 'cache-and-network'>;
type ClientParseError
type ClientParseError = InvariantError & { parseError: Error;};
type CommonOptions
type CommonOptions<TOptions> = TOptions & { client?: ApolloClient<object>;};
type DiffQueryAgainstStoreOptions
type DiffQueryAgainstStoreOptions = ReadQueryOptions & { returnPartialData?: boolean;};
type DocumentTransformCacheKey
type DocumentTransformCacheKey = ReadonlyArray<unknown>;
type ErrorPolicy
type ErrorPolicy = 'none' | 'ignore' | 'all';
errorPolicy determines the level of events for errors in the execution result. The options are: - none (default): any errors from the request are treated like runtime errors and the observable is stopped - ignore: errors from the request do not stop the observable, but also don't call
next
- all: errors are treated like data and will notify observables
type ExecutionPatchResult
type ExecutionPatchResult< TData = Record<string, any>, TExtensions = Record<string, any>> = | ExecutionPatchInitialResult<TData, TExtensions> | ExecutionPatchIncrementalResult<TData, TExtensions>;
type FetchPolicy
type FetchPolicy = | 'cache-first' | 'network-only' | 'cache-only' | 'no-cache' | 'standby';
fetchPolicy determines where the client may return a result from. The options are: - cache-first (default): return result from cache. Only fetch from network if cached result is not available. - cache-and-network: return result from cache first (if it exists), then return network result once it's available. - cache-only: return result from cache if available, fail otherwise. - no-cache: return result from network, fail if network call doesn't succeed, don't save to cache - network-only: return result from network, fail if network call doesn't succeed, save to cache - standby: only for queries that aren't actively watched, but should be available for refetch and updateQueries.
type FetchResult
type FetchResult< TData = Record<string, any>, TContext = Record<string, any>, TExtensions = Record<string, any>> = | SingleExecutionResult<TData, TContext, TExtensions> | ExecutionPatchResult<TData, TExtensions>;
type FieldMergeFunction
type FieldMergeFunction< TExisting = any, TIncoming = TExisting, TOptions extends FieldFunctionOptions = FieldFunctionOptions> = ( existing: SafeReadonly<TExisting> | undefined, incoming: SafeReadonly<TIncoming>, options: TOptions) => SafeReadonly<TExisting>;
type FieldPolicy
type FieldPolicy< TExisting = any, TIncoming = TExisting, TReadResult = TIncoming, TOptions extends FieldFunctionOptions = FieldFunctionOptions> = { keyArgs?: KeySpecifier | KeyArgsFunction | false; read?: FieldReadFunction<TExisting, TReadResult, TOptions>; merge?: FieldMergeFunction<TExisting, TIncoming, TOptions> | boolean;};
type FieldReadFunction
type FieldReadFunction< TExisting = any, TReadResult = TExisting, TOptions extends FieldFunctionOptions = FieldFunctionOptions> = ( existing: SafeReadonly<TExisting> | undefined, options: TOptions) => TReadResult | undefined;
type FragmentMatcher
type FragmentMatcher = ( rootValue: any, typeCondition: string, context: any) => boolean;
type FragmentType
type FragmentType<TData> = [TData] extends [ { ' $fragmentName'?: infer TKey; }] ? TKey extends string ? { ' $fragmentRefs'?: { [key in TKey]: TData; }; } : never : never;
type IdGetter
type IdGetter = (value: IdGetterObj) => string | undefined;
type InternalRefetchQueriesInclude
type InternalRefetchQueriesInclude = | InternalRefetchQueryDescriptor[] | RefetchQueriesIncludeShorthand;
type InternalRefetchQueriesMap
type InternalRefetchQueriesMap<TResult> = Map< ObservableQuery<any>, InternalRefetchQueriesResult<TResult>>;
type InternalRefetchQueriesResult
type InternalRefetchQueriesResult<TResult> = TResult extends boolean ? Promise<ApolloQueryResult<any>> : TResult;
type InternalRefetchQueryDescriptor
type InternalRefetchQueryDescriptor = RefetchQueryDescriptor | QueryOptions;
type LazyQueryExecFunction
type LazyQueryExecFunction<TData, TVariables extends OperationVariables> = ( options?: Partial<LazyQueryHookExecOptions<TData, TVariables>>) => Promise<QueryResult<TData, TVariables>>;
type LazyQueryResult
type LazyQueryResult<TData, TVariables extends OperationVariables> = QueryResult< TData, TVariables>;
Deprecated
This type will be removed in the next major version of Apollo Client
type LazyQueryResultTuple
type LazyQueryResultTuple<TData, TVariables extends OperationVariables> = [ execute: LazyQueryExecFunction<TData, TVariables>, result: QueryResult<TData, TVariables>];
type LoadableQueryHookFetchPolicy
type LoadableQueryHookFetchPolicy = Extract< WatchQueryFetchPolicy, 'cache-first' | 'network-only' | 'no-cache' | 'cache-and-network'>;
type LoadQueryFunction
type LoadQueryFunction<TVariables extends OperationVariables> = ( ...args: [TVariables] extends [never] ? [] : {} extends OnlyRequiredProperties<TVariables> ? [variables?: TVariables] : [variables: TVariables]) => void;
type Masked
type Masked<TData> = TData & { __masked?: true;};
Marks a type as masked. This is used by
MaybeMasked
when determining whether to use the masked or unmasked type.
type MaskedDocumentNode
type MaskedDocumentNode< TData = { [key: string]: any; }, TVariables = { [key: string]: any; }> = TypedDocumentNode<Masked<TData>, TVariables>;
Marks a type as masked. This is a shortcut for
TypedDocumentNode<Masked<TData>, TVariables>
type MaybeMasked
type MaybeMasked<TData> = DataMasking extends { mode: 'unmask';} ? TData extends any ? true extends IsAny<TData> ? TData : TData extends { __masked?: true; } ? Prettify<RemoveMaskedMarker<TData>> : Unmasked<TData> : never : DataMasking extends { mode: 'preserveTypes'; } ? TData : TData;
Returns TData as either masked or unmasked depending on whether masking is enabled.
type MethodKeys
type MethodKeys<T> = { [P in keyof T]: T[P] extends Function ? P : never;}[keyof T];
type MutationFetchPolicy
type MutationFetchPolicy = Extract<FetchPolicy, 'network-only' | 'no-cache'>;
type MutationFunction
type MutationFunction< TData = any, TVariables = OperationVariables, TContext = DefaultContext, TCache extends ApolloCache<any> = ApolloCache<any>> = ( options?: MutationFunctionOptions<TData, TVariables, TContext, TCache>) => Promise<FetchResult<MaybeMasked<TData>>>;
type MutationQueryReducer
type MutationQueryReducer<T> = ( previousResult: Record<string, any>, options: { mutationResult: FetchResult<Unmasked<T>>; queryName: string | undefined; queryVariables: Record<string, any>; }) => Record<string, any>;
type MutationQueryReducersMap
type MutationQueryReducersMap< T = { [key: string]: any; }> = { [queryName: string]: MutationQueryReducer<T>;};
type MutationTuple
type MutationTuple< TData, TVariables, TContext = DefaultContext, TCache extends ApolloCache<any> = ApolloCache<any>> = [ mutate: ( options?: MutationFunctionOptions<TData, TVariables, TContext, TCache> ) => Promise<FetchResult<MaybeMasked<TData>>>, result: MutationResult<TData>];
type MutationUpdaterFn
type MutationUpdaterFn< T = { [key: string]: any; }> = (cache: ApolloCache<T>, mutationResult: FetchResult<T>) => void;
Deprecated
Use
MutationUpdaterFunction
instead.
type MutationUpdaterFunction
type MutationUpdaterFunction< TData, TVariables, TContext, TCache extends ApolloCache<any>> = ( cache: TCache, result: Omit<FetchResult<Unmasked<TData>>, 'context'>, options: { context?: TContext; variables?: TVariables; }) => void;
type NextLink
type NextLink = (operation: Operation) => Observable<FetchResult>;
type NoInfer
type NoInfer<T> = [T][T extends any ? 0 : never];
Helper type that allows using a type in a way that cannot be "widened" by inference on the value it is used on.
This type was first suggested [in this Github discussion](https://github.com/microsoft/TypeScript/issues/14829#issuecomment-504042546).
Example usage:
export function useQuery<TData = any,TVariables extends OperationVariables = OperationVariables,>(query: DocumentNode | TypedDocumentNode<TData, TVariables>,options: QueryHookOptions<NoInfer<TData>, NoInfer<TVariables>> = Object.create(null),)In this case,
TData
andTVariables
should be inferred fromquery
, but never widened from something inoptions
.So, in this code example:
declare const typedNode: TypedDocumentNode<{ foo: string}, { bar: number }>const { variables } = useQuery(typedNode, { variables: { bar: 4, nonExistingVariable: "string" } });Without the use of
NoInfer
,variables
would now be of the type{ bar: number, nonExistingVariable: "string" }
. WithNoInfer
, it will instead give an error onnonExistingVariable
.
type OnQueryUpdated
type OnQueryUpdated<TResult> = ( observableQuery: ObservableQuery<any>, diff: Cache.DiffResult<any>, lastDiff: Cache.DiffResult<any> | undefined) => boolean | TResult;
type OperationVariables
type OperationVariables = Record<string, any>;
type OptimisticStoreItem
type OptimisticStoreItem = { id: string; data: NormalizedCacheObject; transaction: Transaction<NormalizedCacheObject>;};
type Path
type Path = ReadonlyArray<string | number>;
type PossibleTypesMap
type PossibleTypesMap = { [supertype: string]: string[];};
type PreloadQueryFetchPolicy
type PreloadQueryFetchPolicy = Extract< WatchQueryFetchPolicy, 'cache-first' | 'network-only' | 'no-cache' | 'cache-and-network'>;
type PreloadQueryOptions
type PreloadQueryOptions< TVariables extends OperationVariables = OperationVariables> = { /** * 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 * * Using `canonizeResults` can result in memory leaks so we generally do not recommend using this option anymore. A future version of Apollo Client will contain a similar feature without the risk of memory leaks. */ canonizeResults?: boolean; /** * If you're using [Apollo Link](https://www.apollographql.com/docs/react/api/link/introduction/), this object is the initial value of the `context` object that's passed along your link chain. * * @docGroup * * 2. Networking options */ context?: DefaultContext; /** * Specifies how the query handles a response that returns both GraphQL errors and partial results. * * For details, see [GraphQL error policies](https://www.apollographql.com/docs/react/data/error-handling/#graphql-error-policies). * * The default value is `none`, meaning that the query result includes error details but not partial results. * * @docGroup * * 1. Operation options */ errorPolicy?: ErrorPolicy; /** * Specifies how the query interacts with the Apollo Client 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](https://www.apollographql.com/docs/react/data/queries/#setting-a-fetch-policy). * * The default value is `cache-first`. * * @docGroup * * 3. Caching options */ fetchPolicy?: PreloadQueryFetchPolicy; /** * If `true`, the query can return partial results from the cache if the cache doesn't contain results for all queried fields. * * The default value is `false`. * * @docGroup * * 3. Caching options */ returnPartialData?: boolean; /** * Specifies whether a `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. * * @docGroup * * 3. Caching options */ refetchWritePolicy?: RefetchWritePolicy;} & VariablesOption<TVariables>;
type QueryTuple
type QueryTuple<TData, TVariables extends OperationVariables> = LazyQueryResultTuple< TData, TVariables>;
Deprecated
This type will be removed in the next major version of Apollo Client
type ReadQueryOptions
type ReadQueryOptions = { /** * The Apollo Client store object. */ store: NormalizedCache; /** * A parsed GraphQL query document. */ query: DocumentNode; variables?: Object; previousResult?: any; /** * @deprecated * Using `canonizeResults` can result in memory leaks so we generally do not * recommend using this option anymore. * A future version of Apollo Client will contain a similar feature without * the risk of memory leaks. */ canonizeResults?: boolean; rootId?: string; config?: ApolloReducerConfig;};
type RefetchQueriesFunction
type RefetchQueriesFunction = (...args: any[]) => InternalRefetchQueriesInclude;
type RefetchQueriesInclude
type RefetchQueriesInclude = | RefetchQueryDescriptor[] | RefetchQueriesIncludeShorthand;
type RefetchQueriesPromiseResults
type RefetchQueriesPromiseResults<TResult> = IsStrictlyAny<TResult> extends true ? any[] : TResult extends boolean ? ApolloQueryResult<any>[] : TResult extends PromiseLike<infer U> ? U[] : TResult[];
type RefetchQueryDescriptor
type RefetchQueryDescriptor = string | DocumentNode;
type RefetchWritePolicy
type RefetchWritePolicy = 'merge' | 'overwrite';
type RequestHandler
type RequestHandler = ( operation: Operation, forward: NextLink) => Observable<FetchResult> | null;
type Resolver
type Resolver = ( rootValue?: any, args?: any, context?: any, info?: { field: FieldNode; fragmentMap: FragmentMap; }) => any;
type ServerError
type ServerError = Error & { response: Response; result: Record<string, any> | string; statusCode: number;};
type ServerParseError
type ServerParseError = Error & { response: Response; statusCode: number; bodyText: string;};
type SkipToken
type SkipToken = typeof skipToken;
type StoreValue
type StoreValue = | number | string | string[] | Reference | Reference[] | null | undefined | void | Object;
type SubscribeToMoreUpdateQueryFn
type SubscribeToMoreUpdateQueryFn< TData = any, TVariables extends OperationVariables = OperationVariables, TSubscriptionData = TData> = { ( /** * @deprecated This value is not type-safe and may contain partial data. This * argument will be removed in the next major version of Apollo Client. Use * `options.previousData` instead for a more type-safe value. */ unsafePreviousData: Unmasked<TData>, options: UpdateQueryOptions<TData, TVariables> & { subscriptionData: { data: Unmasked<TSubscriptionData>; }; } ): Unmasked<TData> | void;};
type SuspenseQueryHookFetchPolicy
type SuspenseQueryHookFetchPolicy = Extract< WatchQueryFetchPolicy, 'cache-first' | 'network-only' | 'no-cache' | 'cache-and-network'>;
type Transaction
type Transaction<T> = (c: ApolloCache<T>) => void;
type TypePolicies
type TypePolicies = { [__typename: string]: TypePolicy;};
type TypePolicy
type TypePolicy = { keyFields?: KeySpecifier | KeyFieldsFunction | false; merge?: FieldMergeFunction | boolean; queryType?: true; mutationType?: true; subscriptionType?: true; fields?: { [fieldName: string]: FieldPolicy<any> | FieldReadFunction<any>; };};
type Unmasked
type Unmasked<TData> = true extends IsAny<TData> ? TData : TData extends object ? true extends ContainsFragmentsRefs<TData> ? UnwrapFragmentRefs<RemoveMaskedMarker<RemoveFragmentName<TData>>> : TData : TData;
Unmasks a type to provide its full result.
type UpdateQueryOptions
type UpdateQueryOptions<TData, TVariables> = { variables?: TVariables;} & ( | { /** * Indicate if the previous query result has been found fully in the cache. */ complete: true; previousData: Unmasked<TData>; } | { /** * Indicate if the previous query result has not been found fully in the cache. * Might have partial or missing data. */ complete: false; previousData: DeepPartial<Unmasked<TData>> | undefined; });
type UseBackgroundQueryResult
type UseBackgroundQueryResult< TData = unknown, TVariables extends OperationVariables = OperationVariables> = { /** * A function that enables you to execute a [subscription](https://www.apollographql.com/docs/react/data/subscriptions/), 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. */ subscribeToMore: SubscribeToMoreFunction<TData, TVariables>; /** * A function that helps you fetch the next set of results for a [paginated list field](https://www.apollographql.com/docs/react/pagination/core-api/). */ fetchMore: FetchMoreFunction<TData, TVariables>; /** * Update the variables of this observable query, and fetch the new results. This method should be preferred over `setVariables` in most use cases. * * @param variables - The new set of variables. If there are missing variables, the previous values of those variables will be used. */ refetch: RefetchFunction<TData, TVariables>;};
type UseFragmentResult
type UseFragmentResult<TData> = | { data: MaybeMasked<TData>; complete: true; missing?: never; } | { data: DeepPartial<MaybeMasked<TData>>; complete: false; missing?: MissingTree; };
type UseLoadableQueryResult
type UseLoadableQueryResult< TData = unknown, TVariables extends OperationVariables = OperationVariables> = [ loadQuery: LoadQueryFunction<TVariables>, queryRef: QueryRef<TData, TVariables> | null, handlers: { /** * A function that helps you fetch the next set of results for a [paginated list field](https://www.apollographql.com/docs/react/pagination/core-api/). * * * @docGroup * * 3. Helper functions */ fetchMore: FetchMoreFunction<TData, TVariables>; /** * A function that enables you to re-execute the query, optionally passing in new `variables`. * * To guarantee that the refetch performs a network request, its `fetchPolicy` is set to `network-only` (unless the original query's `fetchPolicy` is `no-cache` or `cache-and-network`, which also guarantee a network request). * * See also [Refetching](https://www.apollographql.com/docs/react/data/queries/#refetching). * * @docGroup * * 3. Helper functions */ refetch: RefetchFunction<TData, TVariables>; /** * A function that enables you to execute a [subscription](https://www.apollographql.com/docs/react/data/subscriptions/), 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. */ subscribeToMore: SubscribeToMoreFunction<TData, TVariables>; /** * A function that resets the `queryRef` back to `null`. */ reset: ResetFunction; }];
type UseSuspenseFragmentOptions
type UseSuspenseFragmentOptions<TData, TVariables extends OperationVariables> = { /** * 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. */ fragment: DocumentNode | TypedDocumentNode<TData, TVariables>; /** * 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. */ fragmentName?: string; from: From<TData>; optimistic?: boolean; /** * The instance of `ApolloClient` to use to look up the fragment. * * By default, the instance that's passed down via context is used, but you * can provide a different instance here. * * @docGroup 1. Operation options */ client?: ApolloClient<any>;} & VariablesOption<NoInfer<TVariables>>;
type UseSuspenseFragmentResult
type UseSuspenseFragmentResult<TData> = { data: MaybeMasked<TData>;};
type VariablesOption
type VariablesOption<TVariables extends OperationVariables> = [TVariables] extends [ never] ? { /** * An object containing all of the GraphQL variables your query requires to execute. * * Each key in the object corresponds to a variable name, and that key's value corresponds to the variable value. * * @docGroup * * 1. Operation options */ variables?: Record<string, never>; } : Record<string, never> extends OnlyRequiredProperties<TVariables> ? { /** * An object containing all of the GraphQL variables your query requires to execute. * * Each key in the object corresponds to a variable name, and that key's value corresponds to the variable value. * * @docGroup * * 1. Operation options */ variables?: TVariables; } : { /** * An object containing all of the GraphQL variables your query requires to execute. * * Each key in the object corresponds to a variable name, and that key's value corresponds to the variable value. * * @docGroup * * 1. Operation options */ variables: TVariables; };
type WatchFragmentResult
type WatchFragmentResult<TData> = | { data: MaybeMasked<TData>; complete: true; missing?: never; } | { data: DeepPartial<MaybeMasked<TData>>; complete: false; missing: MissingTree; };
Watched fragment results.
type WatchQueryFetchPolicy
type WatchQueryFetchPolicy = FetchPolicy | 'cache-and-network';
Namespaces
namespace Cache
namespace Cache {}
interface BatchOptions
interface BatchOptions<TCache extends ApolloCache<any>, TUpdateResult = void> {}
property onWatchUpdated
onWatchUpdated?: ( this: TCache, watch: Cache.WatchOptions, diff: Cache.DiffResult<any>, lastDiff?: Cache.DiffResult<any> | undefined) => any;
property optimistic
optimistic?: string | boolean;
property removeOptimistic
removeOptimistic?: string;
method update
update: (cache: TCache) => TUpdateResult;
interface DiffOptions
interface DiffOptions<TData = any, TVariables = any> extends Omit<ReadOptions<TVariables, TData>, 'rootId'> {}
interface EvictOptions
interface EvictOptions {}
interface ModifyOptions
interface ModifyOptions<Entity extends Record<string, any> = Record<string, any>> {}
property broadcast
broadcast?: boolean;
property fields
fields: Modifiers<Entity> | AllFieldsModifier<Entity>;
property id
id?: string;
property optimistic
optimistic?: boolean;
interface ReadOptions
interface ReadOptions<TVariables = any, TData = any> extends DataProxy.Query<TVariables, TData> {}
property canonizeResults
canonizeResults?: boolean;
Deprecated
Using
canonizeResults
can result in memory leaks so we generally do not recommend using this option anymore. A future version of Apollo Client will contain a similar feature without the risk of memory leaks.
property optimistic
optimistic: boolean;
property previousResult
previousResult?: any;
property returnPartialData
returnPartialData?: boolean;
property rootId
rootId?: string;
interface ResetOptions
interface ResetOptions {}
property discardWatches
discardWatches?: boolean;
interface WatchOptions
interface WatchOptions<TData = any, TVariables = any> extends DiffOptions<TData, TVariables> {}
interface WriteOptions
interface WriteOptions<TResult = any, TVariables = any> extends Omit<DataProxy.Query<TVariables, TResult>, 'id'>, Omit<DataProxy.WriteOptions<TResult>, 'data'> {}
type WatchCallback
type WatchCallback<TData = any> = ( diff: Cache.DiffResult<TData>, lastDiff?: Cache.DiffResult<TData>) => void;
namespace DataProxy
namespace DataProxy {}
interface Fragment
interface Fragment<TVariables, TData> {}
property fragment
fragment: DocumentNode | TypedDocumentNode<TData, TVariables>;
A GraphQL document created using the
gql
template string tag fromgraphql-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 specifyfragmentName
to select a single.
property fragmentName
fragmentName?: string;
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 yourfragment
document then that fragment will be used.
property id
id?: 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.
property variables
variables?: TVariables;
Any variables that your GraphQL fragments depend on.
interface Query
interface Query<TVariables, TData> {}
property id
id?: 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.
property query
query: DocumentNode | TypedDocumentNode<TData, TVariables>;
The GraphQL query shape to be used constructed using the
gql
template string tag fromgraphql-tag
. The query will be used to determine the shape of the data to be read.
property variables
variables?: TVariables;
Any variables that the GraphQL query may depend on.
interface ReadFragmentOptions
interface ReadFragmentOptions<TData, TVariables> extends Fragment<TVariables, TData> {}
property canonizeResults
canonizeResults?: 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.
Deprecated
Using
canonizeResults
can result in memory leaks so we generally do not recommend using this option anymore. A future version of Apollo Client will contain a similar feature without the risk of memory leaks.
property optimistic
optimistic?: boolean;
Whether to read from optimistic or non-optimistic cache data. If this named option is provided, the optimistic parameter of the readQuery method can be omitted. Defaults to false.
property returnPartialData
returnPartialData?: boolean;
Whether to return incomplete data rather than null. Defaults to false.
interface ReadQueryOptions
interface ReadQueryOptions<TData, TVariables> extends Query<TVariables, TData> {}
property canonizeResults
canonizeResults?: 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.
Deprecated
Using
canonizeResults
can result in memory leaks so we generally do not recommend using this option anymore. A future version of Apollo Client will contain a similar feature without the risk of memory leaks.
property optimistic
optimistic?: boolean;
Whether to read from optimistic or non-optimistic cache data. If this named option is provided, the optimistic parameter of the readQuery method can be omitted. Defaults to false.
property returnPartialData
returnPartialData?: boolean;
Whether to return incomplete data rather than null. Defaults to false.
interface UpdateFragmentOptions
interface UpdateFragmentOptions<TData, TVariables> extends Omit< ReadFragmentOptions<TData, TVariables> & WriteFragmentOptions<TData, TVariables>, 'data' > {}
interface UpdateQueryOptions
interface UpdateQueryOptions<TData, TVariables> extends Omit< ReadQueryOptions<TData, TVariables> & WriteQueryOptions<TData, TVariables>, 'data' > {}
interface WriteFragmentOptions
interface WriteFragmentOptions<TData, TVariables> extends Fragment<TVariables, TData>, WriteOptions<TData> {}
interface WriteOptions
interface WriteOptions<TData> {}
interface WriteQueryOptions
interface WriteQueryOptions<TData, TVariables> extends Query<TVariables, TData>, WriteOptions<TData> {}
type DiffResult
type DiffResult<T> = { result?: T; complete?: boolean; missing?: MissingFieldError[]; fromOptimisticTransaction?: boolean;};
namespace parser
namespace parser {}
function resetCache
resetCache: () => void;
Package Files (64)
- cache/core/cache.d.ts
- cache/core/types/Cache.d.ts
- cache/core/types/DataProxy.d.ts
- cache/core/types/common.d.ts
- cache/inmemory/helpers.d.ts
- cache/inmemory/inMemoryCache.d.ts
- cache/inmemory/policies.d.ts
- cache/inmemory/reactiveVars.d.ts
- cache/inmemory/types.d.ts
- core/ApolloClient.d.ts
- core/LocalState.d.ts
- core/ObservableQuery.d.ts
- core/networkStatus.d.ts
- core/types.d.ts
- core/watchQueryOptions.d.ts
- errors/index.d.ts
- index.d.ts
- link/core/ApolloLink.d.ts
- link/core/concat.d.ts
- link/core/empty.d.ts
- link/core/execute.d.ts
- link/core/from.d.ts
- link/core/split.d.ts
- link/core/types.d.ts
- link/http/HttpLink.d.ts
- link/http/checkFetcher.d.ts
- link/http/createHttpLink.d.ts
- link/http/createSignalIfSupported.d.ts
- link/http/parseAndCheckHttpResponse.d.ts
- link/http/rewriteURIForGET.d.ts
- link/http/selectHttpOptionsAndBody.d.ts
- link/http/selectURI.d.ts
- link/http/serializeFetchParameter.d.ts
- link/utils/fromError.d.ts
- link/utils/fromPromise.d.ts
- link/utils/throwServerError.d.ts
- link/utils/toPromise.d.ts
- masking/types.d.ts
- react/context/ApolloConsumer.d.ts
- react/context/ApolloContext.d.ts
- react/context/ApolloProvider.d.ts
- react/hooks/constants.d.ts
- react/hooks/useApolloClient.d.ts
- react/hooks/useBackgroundQuery.d.ts
- react/hooks/useFragment.d.ts
- react/hooks/useLazyQuery.d.ts
- react/hooks/useLoadableQuery.d.ts
- react/hooks/useMutation.d.ts
- react/hooks/useQuery.d.ts
- react/hooks/useQueryRefHandlers.d.ts
- react/hooks/useReactiveVar.d.ts
- react/hooks/useReadQuery.d.ts
- react/hooks/useSubscription.d.ts
- react/hooks/useSuspenseFragment.d.ts
- react/hooks/useSuspenseQuery.d.ts
- react/internal/cache/QueryReference.d.ts
- react/internal/cache/getSuspenseCache.d.ts
- react/parser/index.d.ts
- react/query-preloader/createQueryPreloader.d.ts
- react/types/types.d.ts
- utilities/common/mergeOptions.d.ts
- utilities/graphql/DocumentTransform.d.ts
- utilities/graphql/storeUtils.d.ts
- utilities/types/NoInfer.d.ts
Dependencies (13)
Dev Dependencies (93)
- @actions/github-script
- @arethetypeswrong/cli
- @ark/attest
- @babel/parser
- @changesets/changelog-github
- @changesets/cli
- @eslint/compat
- @eslint/eslintrc
- @eslint/js
- @graphql-tools/merge
- @graphql-tools/schema
- @graphql-tools/utils
- @microsoft/api-extractor
- @rollup/plugin-node-resolve
- @size-limit/esbuild-why
- @size-limit/preset-small-lib
- @testing-library/dom
- @testing-library/jest-dom
- @testing-library/react
- @testing-library/react-render-stream
- @testing-library/user-event
- @tsconfig/node20
- @types/bytes
- @types/fetch-mock
- @types/glob
- @types/hoist-non-react-statics
- @types/jest
- @types/lodash
- @types/node
- @types/node-fetch
- @types/prop-types
- @types/react
- @types/react-dom
- @types/relay-runtime
- @types/use-sync-external-store
- @typescript-eslint/eslint-plugin
- @typescript-eslint/parser
- @typescript-eslint/rule-tester
- @typescript-eslint/types
- @typescript-eslint/utils
- acorn
- ajv
- blob-polyfill
- bytes
- cross-fetch
- eslint
- eslint-import-resolver-typescript
- eslint-plugin-import
- eslint-plugin-local-rules
- eslint-plugin-react-compiler
- eslint-plugin-react-hooks
- eslint-plugin-testing-library
- expect-type
- fetch-mock
- glob
- globals
- graphql
- graphql-17-alpha2
- graphql-ws
- jest
- jest-environment-jsdom
- jest-junit
- lodash
- patch-package
- pkg-pr-new
- prettier
- react
- react-17
- react-18
- react-dom
- react-dom-17
- react-dom-18
- react-error-boundary
- recast
- resolve
- rimraf
- rollup
- rollup-plugin-cleanup
- rollup-plugin-terser
- rxjs
- size-limit
- subscriptions-transport-ws
- terser
- ts-api-utils
- ts-jest
- ts-jest-resolver
- ts-morph
- ts-node
- tsx
- typedoc
- typescript
- web-streams-polyfill
- whatwg-fetch
Peer Dependencies (5)
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/@apollo/client
.
- Markdown[](https://www.jsdocs.io/package/@apollo/client)
- HTML<a href="https://www.jsdocs.io/package/@apollo/client"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 9146 ms. - Missing or incorrect documentation? Open an issue for this package.