ApolloProvider
component
The ApolloProvider
component leverages React's Context API to make a configured Apollo Client instance available throughout a React component tree. This component can be imported directly from the @apollo/client
package.
ApolloConsumer
component
One way to access the configured Apollo Client instance directly is to create an ApolloConsumer
component and provide a render prop function as its child. The render prop function will be called with your ApolloClient
instance as its only argument. You can think of the ApolloConsumer
component as similar to the Consumer
component from the React Context API .
Name / Type
Description
query
DocumentNode | TypedDocumentNode<TData, TVariables>
A GraphQL query document parsed into an AST by gql
.
Options to control how the query is executed.
Show/hide child attributesOperation options
(data: MaybeMasked<TData>) => void
(error: ApolloError) => void
Networking options
If you're using Apollo Link, this object is the initial value of the context
object that's passed along your link chain.
A callback function that's called whenever a refetch attempt occurs while polling. If the function returns true
, the refetch is skipped and not reattempted until the next poll interval.
Caching options
Defaults to the initial value of options.fetchPolicy, but can be explicitly configured to specify the WatchQueryFetchPolicy to revert back to whenever variables change (unless nextFetchPolicy intervenes).
WatchQueryFetchPolicy | ((this: WatchQueryOptions<TVariables, TData>, currentFetchPolicy: WatchQueryFetchPolicy, context: NextFetchPolicyContext<TData, TVariables>) => WatchQueryFetchPolicy)
Specifies the FetchPolicy
to be used after this query has completed.
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.
Other
ResultQuery result object
QueryResult<TData, TVariables>
Show/hide child attributes
Operation data
MaybeMasked<TData> | undefined
An object containing the variables that were provided for the query.
Network info
The instance of Apollo Client that executed the query. Can be useful for manually executing followup queries or writing data to the cache.
If true
, the query is still in flight and results have not yet been returned.
Helper functions
<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>>>
(variables?: Partial<TVariables>) => Promise<ApolloQueryResult<MaybeMasked<TData>>>
(pollInterval: number) => void
A function that instructs the query to begin re-executing at a specified interval (in milliseconds).
A function that instructs the query to stop polling after a previous call to startPolling
.
SubscribeToMoreFunction<TData, TVariables>
(mapFn: UpdateQueryMapFn<TData, TVariables>) => void
Other
ObservableQuery<TData, TVariables>
A reference to the internal ObservableQuery
used by the hook.
ReadonlyArray<GraphQLFormattedError>
Example Signature(src/react/hooks/useLazyQuery.ts) Parameters
Name / Type
Description
query
DocumentNode | TypedDocumentNode<TData, TVariables>
A GraphQL query document parsed into an AST by gql
.
Default options to control how the query is executed.
Show/hide child attributesOperation options
(data: MaybeMasked<TData>) => void
(error: ApolloError) => void
Networking options
If you're using Apollo Link, this object is the initial value of the context
object that's passed along your link chain.
A callback function that's called whenever a refetch attempt occurs while polling. If the function returns true
, the refetch is skipped and not reattempted until the next poll interval.
Caching options
Defaults to the initial value of options.fetchPolicy, but can be explicitly configured to specify the WatchQueryFetchPolicy to revert back to whenever variables change (unless nextFetchPolicy intervenes).
WatchQueryFetchPolicy | ((this: WatchQueryOptions<TVariables, TData>, currentFetchPolicy: WatchQueryFetchPolicy, context: NextFetchPolicyContext<TData, TVariables>) => WatchQueryFetchPolicy)
Specifies the FetchPolicy
to be used after this query has completed.
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.
Other
ResultA tuple of two values:
Name / Type
Description
execute
(options?: LazyQueryHookOptions<TVariables>) => Promise<LazyQueryResult<TData, TVariables>>
Function that can be triggered to execute the suspended query. After being called, useLazyQuery
behaves just like useQuery
. The useLazyQuery
function returns a promise that fulfills with a query result when the query succeeds or fails.
result
QueryResult<TData, TVariables>
The result of the query. See the useQuery
hook for more details.
Operation data
MaybeMasked<TData> | undefined
An object containing the variables that were provided for the query.
Network info
The instance of Apollo Client that executed the query. Can be useful for manually executing followup queries or writing data to the cache.
If true
, the query is still in flight and results have not yet been returned.
Helper functions
<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>>>
(variables?: Partial<TVariables>) => Promise<ApolloQueryResult<MaybeMasked<TData>>>
(pollInterval: number) => void
A function that instructs the query to begin re-executing at a specified interval (in milliseconds).
A function that instructs the query to stop polling after a previous call to startPolling
.
SubscribeToMoreFunction<TData, TVariables>
(mapFn: UpdateQueryMapFn<TData, TVariables>) => void
Other
ObservableQuery<TData, TVariables>
A reference to the internal ObservableQuery
used by the hook.
ReadonlyArray<GraphQLFormattedError>
Example Signature(src/react/hooks/useMutation.ts) Parameters
Name / Type
Description
mutation
DocumentNode | TypedDocumentNode<TData, TVariables>
A GraphQL mutation document parsed into an AST by gql
.
options
(optional)
MutationHookOptions<NoInfer<TData>, NoInfer<TVariables>, TContext, TCache>
Options to control how the mutation is executed.
Show/hide child attributesOperation options
(data: MaybeMasked<TData>, clientOptions?: BaseMutationOptions) => void
(error: ApolloError, clientOptions?: BaseMutationOptions) => void
((result: FetchResult<Unmasked<TData>>) => InternalRefetchQueriesInclude) | InternalRefetchQueriesInclude
Networking options
If you're using Apollo Link, this object is the initial value of the context
object that's passed along your link chain.
Caching options
Unmasked<NoInfer<TData>> | ((vars: TVariables, { IGNORE }: { IGNORE: IgnoreModifier; }) => Unmasked<NoInfer<TData>> | IgnoreModifier)
MutationUpdaterFunction<TData, TVariables, TContext, TCache>
Other
To avoid retaining sensitive information from mutation root field arguments, Apollo Client v3.4+ automatically clears any ROOT_MUTATION
fields from the cache after each mutation finishes. If you need this information to remain in the cache, you can prevent the removal by passing keepRootFields: true
to the mutation. ROOT_MUTATION
result data are also passed to the mutation update
function, so we recommend obtaining the results that way, rather than using this option, if possible.
MutationQueryReducersMap<TData>
A MutationQueryReducersMap
, which is map from query names to mutation query reducers. Briefly, this map defines how to incorporate the results of the mutation into the results of queries that are currently being watched by your application.
A tuple of two values:
Name / Type
Description
mutate
( options?: MutationFunctionOptions<TData, TVariables> ) => Promise<FetchResult<TData>>
A function to trigger the
mutation
from your UI. You can optionally pass this function any of the following options:
awaitRefetchQueries
context
fetchPolicy
onCompleted
onError
optimisticResponse
refetchQueries
onQueryUpdated
update
variables
client
Any option you pass here overrides any existing value for that option that you passed to
useMutation
.
The mutate function returns a promise that fulfills with your
mutation
result.
result
MutationResult<TData>
The result of the mutation.
Show/hide child attributesIf true
, the mutation's mutate function has been called.
MaybeMasked<TData> | null
The data returned from your mutation. Can be undefined
if ignoreResults
is true
.
If true
, the mutation is currently in flight.
A function that you can call to reset the mutation's result to its initial, uncalled state.
Example Signature(src/react/hooks/useSubscription.ts) ParametersName / Type
Description
subscription
DocumentNode | TypedDocumentNode<TData, TVariables>
A GraphQL subscription document parsed into an AST by gql
.
Options to control how the subscription is executed.
Show/hide child attributesAn ApolloClient
instance. By default useSubscription
/ Subscription
uses the client passed down via context, but a different client can be passed in.
Shared context between your component and your network interface (Apollo Link).
Specifies the ErrorPolicy
to be used for this operation
Shared context between your component and your network interface (Apollo Link).
Allows the registration of a callback function that will be triggered each time the useSubscription
Hook / Subscription
component completes the subscription.
(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 callback options
object param consists of the current Apollo Client instance in client
, and the received subscription data in data
.
(error: ApolloError) => void
Allows the registration of a callback function that will be triggered each time the useSubscription
Hook / Subscription
component receives an error.
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
or variables
) changes.
Determines if the current subscription should be skipped. Useful if, for example, variables depend on previous queries and are not ready yet.
An object containing all of the variables your subscription needs to execute
(options: OnSubscriptionDataOptions<TData>) => any
Result
Query result object
{
restart: () => void;
loading: boolean;
data?: TData | undefined;
error?: ApolloError;
variables?: TVariables | undefined;
}
useFragment
Requires ⥠3.8.0
useFragment
represents a lightweight live binding into the Apollo Client Cache and enables Apollo Client to broadcast very specific fragment results to individual components. This hook returns an always-up-to-date view of whatever data the cache currently contains for a given fragment. useFragment
never triggers network requests of its own.
Note that the useQuery
hook remains the primary hook responsible for querying and populating data in the cache (see the API reference). As a result, the component reading the fragment data via useFragment
is still subscribed to all changes in the query data, but receives updates only when that fragment's specific data change.
ExampleNote: this hook was introduced in
3.7.0
as experimental but stabilized in3.8.0
. In3.7.x
and3.8.0-alpha.x
releases, this hook is exported asuseFragment_experimental
. Starting with3.8.0-beta.0
and greater the_experimental
suffix was removed in its named export.
To view a useFragment
example, see the Fragments page.
options
Result useSuspenseQuery
Requires ⥠3.8.0
For a detailed explanation of useSuspenseQuery
, see the fetching with Suspense reference.
query
options
Instead of passing a SuspenseQueryHookOptions
object into the hook, you can also pass a skipToken
to prevent the useSuspenseQuery
hook from executing the query or suspending.
Properties
Name / Type
Description
Operation options
Networking options
If you're using Apollo Link, this object is the initial value of the context
object that's passed along your link chain.
Caching options
SuspenseQueryHookFetchPolicy
Other
ResultuseBackgroundQuery
Requires ⥠3.8.0
For a detailed explanation of useBackgroundQuery
, see the fetching with Suspense reference.
query
options
Instead of passing a BackgroundQueryHookOptions
object into the hook, you can also pass a skipToken
to prevent the useBackgroundQuery
hook from executing the query.
If no query has been executed yet and you skip the query, the hook will return undefined
instead of a queryRef
.
useReadQuery
Requires ⥠3.8.0
For a detailed explanation of useReadQuery
, see the fetching with Suspense reference.
See the example in the useBackgroundQuery
section above.
queryRef
Result Example Signature(src/react/hooks/useLoadableQuery.ts) Parameters
Name / Type
Description
query
DocumentNode | TypedDocumentNode<TData, TVariables>
A GraphQL query document parsed into an AST by gql
.
Options to control how the query is executed.
Show/hide child attributesOperation options
Networking options
If you're using Apollo Link, this object is the initial value of the context
object that's passed along your link chain.
Caching options
LoadableQueryHookFetchPolicy
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.
Other
ResultA tuple of three values:
Name / Type
Description
loadQuery
LoadQueryFunction<TVariables>
A function used to imperatively load a query. Calling this function will create or update the queryRef
returned by useLoadableQuery
, which should be passed to useReadQuery
.
queryRef
QueryRef<TData, TVariables> | null
The queryRef
used by useReadQuery
to read the query result.
handlers
{ fetchMore: FetchMoreFunction<TData, TVariables>; refetch: RefetchFunction<TData, TVariables>; reset: ResetFunction; }
Additional handlers used for the query, such as refetch
.
skipToken
Requires ⥠3.8.0
While not a hook by itself, skipToken
is designed to be used with useSuspenseQuery
and useBackgroundQuery
. If a skipToken
is passed into one of those hooks instead of the options
object, that hook will not cause any requests or suspenseful behavior, while keeping the last data
available.
Note: Why do we recommendskipToken
over{ skip: true }
?Imagine this very common scenario forskip
: You want to skip your query if a certain variable is not set. You might be tempted to write something like this:But in that case, TypeScript will complain:To get around that, you have to tell TypeScript to ignore the fact thatid
could beundefined
:Alternatively, you could also use some obscure default value:What both of these solutions have in common: They hide a potential bug. If yourskip
logic becomes more complex in the future, you might accidentally introduce a bug that causes your query not to be skipped, even thoughid
is stillundefined
- and TypeScript won't be able to warn you about it.So instead, we recommend usingskipToken
, as that will work without a lie to the compiler or an obscure default value:In this case, it becomes apparent for TypeScript that there is a direct connection between skipping and thevariables
option - and it will work without unsafe workarounds.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4