@apollo/react-hooks
API reference
Installation
Text
1npm install @apollo/react-hooks
useQuery
Example
JavaScript
1import { useQuery } from '@apollo/react-hooks';
2import gql from 'graphql-tag';
3
4const GET_GREETING = gql`
5 query getGreeting($language: String!) {
6 greeting(language: $language) {
7 message
8 }
9 }
10`;
11
12function 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}
Refer to the Queries section for a more in-depth overview of
useQuery
.
Function Signature
TypeScript
1function useQuery<TData = any, TVariables = OperationVariables>(
2 query: DocumentNode,
3 options?: QueryHookOptions<TData, TVariables>,
4): QueryResult<TData, TVariables> {}
Params
query
Param | Type | Description |
---|---|---|
query | DocumentNode | A GraphQL query document parsed into an AST by graphql-tag . |
options
Option | Type | Description |
---|---|---|
query | DocumentNode | A GraphQL query document parsed into an AST by graphql-tag . Optional for the useQuery Hook since the query can be passed in as the first parameter to the Hook. Required for the Query component. |
variables | { [key: string]: any } | An object containing all of the variables your query needs to execute |
pollInterval | number | Specifies the interval in ms at which you want your component to poll for data. Defaults to 0 (no polling). |
notifyOnNetworkStatusChange | boolean | Whether updates to the network status or network error should re-render your component. Defaults to false. |
fetchPolicy | FetchPolicy | How you want your component to interact with the Apollo cache. Defaults to "cache-first". |
errorPolicy | ErrorPolicy | How you want your component to handle network and GraphQL errors. Defaults to "none", which means we treat GraphQL errors as runtime errors. |
ssr | boolean | Pass in false to skip your query during server-side rendering. |
displayName | string | The name of your component to be displayed in React DevTools. Defaults to 'Query'. |
skip | boolean | If skip is true, the query will be skipped entirely. Not available with useLazyQuery . |
onCompleted | (data: TData {}) => void | A callback executed once your query successfully completes. |
onError | (error: ApolloError) => void | A callback executed in the event of an error. |
context | Record<string, any> | Shared context between your component and your network interface (Apollo Link). Useful for setting headers from props or sending information to the request function of Apollo Boost. |
partialRefetch | boolean | If true , perform a query refetch if the query result is marked as being partial, and the returned data is reset to an empty Object by the Apollo Client QueryManager (due to a cache miss). The default value is false for backwards-compatibility's sake, but should be changed to true for most use-cases. |
client | ApolloClient | An ApolloClient instance. By default useQuery / Query uses the client passed down via context, but a different client can be passed in. |
returnPartialData | boolean | Opt into receiving partial results from the cache for queries that are not fully satisfied by the cache. false by default. |
Result
Property | Type | Description |
---|---|---|
data | TData | An object containing the result of your GraphQL query. Defaults to undefined . |
loading | boolean | A boolean that indicates whether the request is in flight |
error | ApolloError | A runtime error with graphQLErrors and networkError properties |
variables | { [key: string]: any } | An object containing the variables the query was called with |
networkStatus | NetworkStatus | A number from 1-8 corresponding to the detailed state of your network request. Includes information about refetching and polling status. Used in conjunction with the notifyOnNetworkStatusChange prop. |
refetch | (variables?: TVariables) => Promise<ApolloQueryResult> | A function that allows you to refetch the query and optionally pass in new variables |
fetchMore | ({ query?: DocumentNode, variables?: TVariables, updateQuery: Function}) => Promise<ApolloQueryResult> | A function that enables pagination for your query |
startPolling | (interval: number) => void | This function sets up an interval in ms and fetches the query each time the specified interval passes. |
stopPolling | () => void | This function stops the query from polling. |
subscribeToMore | (options: { document: DocumentNode, variables?: TVariables, updateQuery?: Function, onError?: Function}) => () => void | A function that sets up a subscription . subscribeToMore returns a function that you can use to unsubscribe. |
updateQuery | (previousResult: TData, options: { variables: TVariables }) => TData | A function that allows you to update the query's result in the cache outside the context of a fetch, mutation, or subscription |
client | ApolloClient | Your ApolloClient instance. Useful for manually firing queries or writing data to the cache. |
called | boolean | A boolean indicating if the query function has been called, used by useLazyQuery (not set for useQuery / Query ). |
useLazyQuery
Example
JavaScript
1import { useLazyQuery } from "@apollo/react-hooks";
2import gql from "graphql-tag";
3
4const GET_GREETING = gql`
5 query getGreeting($language: String!) {
6 greeting(language: $language) {
7 message
8 }
9 }
10`;
11
12function Hello() {
13 const [loadGreeting, { called, loading, data }] = useLazyQuery(
14 GET_GREETING,
15 { variables: { language: "english" } }
16 );
17 if (called && loading) return <p>Loading ...</p>
18 if (!called) {
19 return <button onClick={() => loadGreeting()}>Load greeting</button>
20 }
21 return <h1>Hello {data.greeting.message}!</h1>;
22}
Refer to the Queries section for a more in-depth overview of
useLazyQuery
.
Function Signature
TypeScript
1function useLazyQuery<TData = any, TVariables = OperationVariables>(
2 query: DocumentNode,
3 options?: LazyQueryHookOptions<TData, TVariables>,
4): [
5 (options?: QueryLazyOptions<TVariables>) => void,
6 QueryResult<TData, TVariables>
7] {}
Params
query
Param | Type | Description |
---|---|---|
query | DocumentNode | A GraphQL query document parsed into an AST by graphql-tag . |
options
Option | Type | Description |
---|---|---|
query | DocumentNode | A GraphQL query document parsed into an AST by graphql-tag . Optional for the useQuery Hook since the query can be passed in as the first parameter to the Hook. Required for the Query component. |
variables | { [key: string]: any } | An object containing all of the variables your query needs to execute |
pollInterval | number | Specifies the interval in ms at which you want your component to poll for data. Defaults to 0 (no polling). |
notifyOnNetworkStatusChange | boolean | Whether updates to the network status or network error should re-render your component. Defaults to false. |
fetchPolicy | FetchPolicy | How you want your component to interact with the Apollo cache. Defaults to "cache-first". |
errorPolicy | ErrorPolicy | How you want your component to handle network and GraphQL errors. Defaults to "none", which means we treat GraphQL errors as runtime errors. |
ssr | boolean | Pass in false to skip your query during server-side rendering. |
displayName | string | The name of your component to be displayed in React DevTools. Defaults to 'Query'. |
skip | boolean | If skip is true, the query will be skipped entirely. Not available with useLazyQuery . |
onCompleted | (data: TData {}) => void | A callback executed once your query successfully completes. |
onError | (error: ApolloError) => void | A callback executed in the event of an error. |
context | Record<string, any> | Shared context between your component and your network interface (Apollo Link). Useful for setting headers from props or sending information to the request function of Apollo Boost. |
partialRefetch | boolean | If true , perform a query refetch if the query result is marked as being partial, and the returned data is reset to an empty Object by the Apollo Client QueryManager (due to a cache miss). The default value is false for backwards-compatibility's sake, but should be changed to true for most use-cases. |
client | ApolloClient | An ApolloClient instance. By default useQuery / Query uses the client passed down via context, but a different client can be passed in. |
returnPartialData | boolean | Opt into receiving partial results from the cache for queries that are not fully satisfied by the cache. false by default. |
Result
Execute function
Param | Type | Description |
---|---|---|
Execute function | options?: QueryLazyOptions<TVariables>) => void | Function that can be triggered to execute the suspended query. After being called, useLazyQuery behaves just like useQuery . |
Result object
Property | Type | Description |
---|---|---|
data | TData | An object containing the result of your GraphQL query. Defaults to undefined . |
loading | boolean | A boolean that indicates whether the request is in flight |
error | ApolloError | A runtime error with graphQLErrors and networkError properties |
variables | { [key: string]: any } | An object containing the variables the query was called with |
networkStatus | NetworkStatus | A number from 1-8 corresponding to the detailed state of your network request. Includes information about refetching and polling status. Used in conjunction with the notifyOnNetworkStatusChange prop. |
refetch | (variables?: TVariables) => Promise<ApolloQueryResult> | A function that allows you to refetch the query and optionally pass in new variables |
fetchMore | ({ query?: DocumentNode, variables?: TVariables, updateQuery: Function}) => Promise<ApolloQueryResult> | A function that enables pagination for your query |
startPolling | (interval: number) => void | This function sets up an interval in ms and fetches the query each time the specified interval passes. |
stopPolling | () => void | This function stops the query from polling. |
subscribeToMore | (options: { document: DocumentNode, variables?: TVariables, updateQuery?: Function, onError?: Function}) => () => void | A function that sets up a subscription . subscribeToMore returns a function that you can use to unsubscribe. |
updateQuery | (previousResult: TData, options: { variables: TVariables }) => TData | A function that allows you to update the query's result in the cache outside the context of a fetch, mutation, or subscription |
client | ApolloClient | Your ApolloClient instance. Useful for manually firing queries or writing data to the cache. |
called | boolean | A boolean indicating if the query function has been called, used by useLazyQuery (not set for useQuery / Query ). |
useMutation
Example
JavaScript
1import { useMutation } from '@apollo/react-hooks';
2import gql from 'graphql-tag';
3
4const ADD_TODO = gql`
5 mutation AddTodo($type: String!) {
6 addTodo(type: $type) {
7 id
8 type
9 }
10 }
11`;
12
13function AddTodo() {
14 let input;
15 const [addTodo, { data }] = useMutation(ADD_TODO);
16
17 return (
18 <div>
19 <form
20 onSubmit={e => {
21 e.preventDefault();
22 addTodo({ variables: { type: input.value } });
23 input.value = '';
24 }}
25 >
26 <input
27 ref={node => {
28 input = node;
29 }}
30 />
31 <button type="submit">Add Todo</button>
32 </form>
33 </div>
34 );
35}
Refer to the Mutations section for a more in-depth overview of
useMutation
.
Function Signature
TypeScript
1function useMutation<TData = any, TVariables = OperationVariables>(
2 mutation: DocumentNode,
3 options?: MutationHookOptions<TData, TVariables>,
4): MutationTuple<TData, TVariables> {}
Params
mutation
Param | Type | Description |
---|---|---|
mutation | DocumentNode | A GraphQL mutation document parsed into an AST by graphql-tag . |
options
Option | Type | Description |
---|---|---|
mutation | DocumentNode | A GraphQL mutation document parsed into an AST by graphql-tag . Optional for the useMutation Hook since the mutation can be passed in as the first parameter to the Hook. Required for the Mutation component. |
variables | { [key: string]: any } | An object containing all of the variables your mutation needs to execute |
update | (cache: DataProxy, mutationResult: FetchResult) | A function used to update the cache after a mutation occurs |
ignoreResults | boolean | If true, the returned data property will not update with the mutation result. |
optimisticResponse | Object | Provide a mutation response before the result comes back from the server |
refetchQueries | Array<string|{ query: DocumentNode, variables?: TVariables}> | ((mutationResult: FetchResult) => Array<string|{ query: DocumentNode, variables?: TVariables}>) | An array or function that allows you to specify which queries you want to refetch after a mutation has occurred. Array values can either be queries (with optional variables) or just the string names of queries to be refeteched. |
awaitRefetchQueries | boolean | Queries refetched as part of refetchQueries are handled asynchronously, and are not waited on before the mutation is completed (resolved). Setting this to true will make sure refetched queries are completed before the mutation is considered done. false by default. |
onCompleted | (data: TData) => void | A callback executed once your mutation successfully completes |
onError | (error: ApolloError) => void | A callback executed in the event of an error. |
context | Record<string, any> | Shared context between your component and your network interface (Apollo Link). Useful for setting headers from props or sending information to the request function of Apollo Boost. |
client | ApolloClient | An ApolloClient instance. By default useMutation / Mutation uses the client passed down via context, but a different client can be passed in. |
Result
Mutate function:
Property | Type | Description |
---|---|---|
mutate | (options?: MutationOptions) => Promise<FetchResult> | A function to trigger a mutation from your UI. You can optionally pass variables , optimisticResponse , refetchQueries , and update in as options, which will override options/props passed to useMutation / Mutation . The function returns a promise that fulfills with your mutation result. |
Mutation result:
Property | Type | Description |
---|---|---|
data | TData | The data returned from your mutation. It can be undefined if ignoreResults is true. |
loading | boolean | A boolean indicating whether your mutation is in flight |
error | ApolloError | Any errors returned from the mutation |
called | boolean | A boolean indicating if the mutate function has been called |
client | ApolloClient | Your ApolloClient instance. Useful for invoking cache methods outside the context of the update function, such as client.writeData and client.readQuery . |
useSubscription
Example
JavaScript
1const COMMENTS_SUBSCRIPTION = gql`
2 subscription onCommentAdded($repoFullName: String!) {
3 commentAdded(repoFullName: $repoFullName) {
4 id
5 content
6 }
7 }
8`;
9
10function DontReadTheComments({ repoFullName }) {
11 const {
12 data: { commentAdded },
13 loading,
14 } = useSubscription(COMMENTS_SUBSCRIPTION, { variables: { repoFullName } });
15 return <h4>New comment: {!loading && commentAdded.content}</h4>;
16}
Refer to the Subscriptions section for a more in-depth overview of
useSubscription
.
Function Signature
TypeScript
1function useSubscription<TData = any, TVariables = OperationVariables>(
2 subscription: DocumentNode,
3 options?: SubscriptionHookOptions<TData, TVariables>,
4): {
5 variables: TVariables;
6 loading: boolean;
7 data?: TData;
8 error?: ApolloError;
9} {}
Params
subscription
Param | Type | Description |
---|---|---|
subscription | DocumentNode | A GraphQL subscription document parsed into an AST by graphql-tag . |
options
Option | Type | Description |
---|---|---|
subscription | DocumentNode | A GraphQL subscription document parsed into an AST by graphql-tag . Optional for the useSubscription Hook since the subscription can be passed in as the first parameter to the Hook. Required for the Subscription component. |
variables | { [key: string]: any } | An object containing all of the variables your subscription needs to execute |
shouldResubscribe | boolean | Determines if your subscription should be unsubscribed and subscribed again |
skip | boolean | If skip is true , the subscription will be skipped entirely |
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 callback options object param consists of the current Apollo Client instance in client , and the received subscription data in subscriptionData . |
fetchPolicy | FetchPolicy | How you want your component to interact with the Apollo cache. Defaults to "cache-first". |
client | ApolloClient | An ApolloClient instance. By default useSubscription / Subscription uses the client passed down via context, but a different client can be passed in. |
Result
Property | Type | Description |
---|---|---|
data | TData | An object containing the result of your GraphQL subscription. Defaults to an empty object. |
loading | boolean | A boolean that indicates whether any initial data has been returned |
error | ApolloError | A runtime error with graphQLErrors and networkError properties |
useApolloClient
Example
JavaScript
1function SomeComponent() {
2 const client = useApolloClient();
3 // `client` is now set to the `ApolloClient` instance being used by the
4 // application (that was configured using something like `ApolloProvider`)
5}
Function Signature
TypeScript
1function useApolloClient(): ApolloClient<object> {}
Result
Param | Type | Description |
---|---|---|
Apollo Client instance | ApolloClient<object> | The ApolloClient instance being used by the application. |
ApolloProvider
Property | Type | Description |
---|---|---|
data | TData | An object containing the result of your GraphQL subscription. Defaults to an empty object. |
loading | boolean | A boolean that indicates whether any initial data has been returned |
error | ApolloError | A runtime error with graphQLErrors and networkError properties |