useQuery

Apollo Client API reference


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 contains loading, error, dataState, and data properties you can use to render your UI.

Refer to the Queries section for a more in-depth overview of useQuery.

Example

JavaScript
1 import { gql } from "@apollo/client";
2 import { useQuery } from "@apollo/client/react";
3 
4 const GET_GREETING = gql`
5   query GetGreeting($language: String!) {
6     greeting(language: $language) {
7       message
8     }
9   }
10 `;
11 
12 function Hello() {
13   const { loading, error, data } = useQuery(GET_GREETING, {
14     variables: { language: "english" },
15   });
16   if (loading) return <p>Loading ...</p>;
17   return <h1>Hello {data.greeting.message}!</h1>;
18 }

Signature

TypeScript
1useQuery<TData, TVariables>(
2  query: DocumentNode | TypedDocumentNode<TData, TVariables>,
3  options: useQuery.Options<TData, TVariables>
4): useQuery.Result<TData, TVariables>

Parameters

Name / Type
Description
query
DocumentNode | TypedDocumentNode<TData, TVariables>

A GraphQL query document parsed into an AST by gql.

options
useQuery.Options<TData, TVariables>

Options to control how the query is executed.

Show/hide child attributes
Operation options
ApolloClient

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.

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

For details, see GraphQL error policies.

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

If true, the query is not executed.

The default value is false.

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.

Networking options
DefaultContext

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

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

The default value is true.

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

The default value is 0 (no polling).

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

Pass false to skip executing the query during server-side rendering.

Caching options
WatchQueryFetchPolicy

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.

The default value is cache-first.

WatchQueryFetchPolicy

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: ApolloClient.WatchQueryOptions<TData, TVariables>, currentFetchPolicy: WatchQueryFetchPolicy, context: InternalTypes.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.

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.

Result

Query result object
useQuery.Result<TData, TVariables>
Show/hide child attributes
Operation data
DataValue.Complete<TData> | DataValue.Streaming<TData> | DataValue.Partial<TData> | undefined

An object containing the result of your GraphQL query after it completes.

This value might be undefined if a query results in one or more errors (depending on the query's errorPolicy).

"complete" | "streaming" | "partial" | "empty"

Describes the completeness of data.

  • empty: No data could be fulfilled from the cache or the result is incomplete. data is undefined.

  • partial: Some data could be fulfilled from the cache but data is incomplete. This is only possible when returnPartialData is true.

  • streaming: data is incomplete as a result of a deferred query and the result is still streaming in.

  • complete: data is a fully satisfied query result fulfilled either from the cache or network.

A single ErrorLike object describing the error that occurred during the latest query execution.

For more information, see Handling operation errors.

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.

TReturnVariables

An object containing the variables that were provided for the query.

Network info
ApolloClient

The instance of Apollo Client that executed the query. Can be useful for manually executing followup queries or writing data to the cache.

boolean

If true, the query is still in flight.

NetworkStatus

A number indicating the current network state of the query's associated request. See possible values.

Used in conjunction with the notifyOnNetworkStatusChange option.

Helper functions
<TFetchData = TData, TFetchVars extends OperationVariables = TVariables>(fetchMoreOptions: ObservableQuery.FetchMoreOptions<TData, TVariables, TFetchData, TFetchVars>) => Promise<ApolloClient.QueryResult<MaybeMasked<TFetchData>>>

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

(variables?: Partial<TVariables>) => Promise<ApolloClient.QueryResult<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 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.

Returns a ResultPromise with an additional .retain() method. Calling .retain() keeps the network operation running even if the ObservableQuery no longer requires the result.

(pollInterval: number) => void

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

() => void

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

SubscribeToMoreFunction<TData, TVariables>

A function that enables you to execute a subscription, usually to subscribe to specific fields that were included in the query.

This function returns another function that you can call to terminate the subscription.

(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 for additional information.

Other
ObservableQuery<TData, TVariables>

A reference to the internal ObservableQuery used by the hook.

Feedback

Edit on GitHub

Ask Community