Docs
Launch GraphOS Studio
You're viewing documentation for a previous version of this software. Switch to the latest stable version.

@apollo/react-hooks

API reference


Installation

npm install @apollo/react-hooks

useQuery

Example

import { useQuery } from '@apollo/react-hooks';
import gql from 'graphql-tag';
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>;
}

Refer to the

section for a more in-depth overview of useQuery.

Function Signature

function useQuery<TData = any, TVariables = OperationVariables>(
query: DocumentNode,
options?: QueryHookOptions<TData, TVariables>,
): QueryResult<TData, TVariables> {}

Params

query

ParamTypeDescription
queryDocumentNodeA GraphQL query document parsed into an AST by graphql-tag.

options

OptionTypeDescription
queryDocumentNodeA 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
pollIntervalnumberSpecifies the interval in ms at which you want your component to poll for data. Defaults to 0 (no polling).
notifyOnNetworkStatusChangebooleanWhether updates to the network status or network error should re-render your component. Defaults to false.
fetchPolicyFetchPolicyHow you want your component to interact with the Apollo cache. Defaults to "cache-first".
errorPolicyErrorPolicyHow you want your component to handle network and GraphQL errors. Defaults to "none", which means we treat GraphQL errors as runtime errors.
ssrbooleanPass in false to skip your query during server-side rendering.
displayNamestringThe name of your component to be displayed in React DevTools. Defaults to 'Query'.
skipbooleanIf skip is true, the query will be skipped entirely. Not available with useLazyQuery.
onCompleted(data: TData | {}) => voidA callback executed once your query successfully completes.
onError(error: ApolloError) => voidA callback executed in the event of an error.
contextRecord<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.
partialRefetchbooleanIf 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.
clientApolloClientAn ApolloClient instance. By default useQuery / Query uses the client passed down via context, but a different client can be passed in.
returnPartialDatabooleanOpt into receiving partial results from the cache for queries that are not fully satisfied by the cache. false by default.

Result

PropertyTypeDescription
dataTDataAn object containing the result of your GraphQL query. Defaults to undefined.
loadingbooleanA boolean that indicates whether the request is in flight
errorApolloErrorA runtime error with graphQLErrors and networkError properties
variables{ [key: string]: any }An object containing the variables the query was called with
networkStatusNetworkStatusA 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) => voidThis function sets up an interval in ms and fetches the query each time the specified interval passes.
stopPolling() => voidThis function stops the query from polling.
subscribeToMore(options: { document: DocumentNode, variables?: TVariables, updateQuery?: Function, onError?: Function}) => () => voidA function that sets up a
subscription
. subscribeToMore returns a function that you can use to unsubscribe.
updateQuery(previousResult: TData, options: { variables: TVariables }) => TDataA function that allows you to update the query's result in the cache outside the context of a fetch, mutation, or subscription
clientApolloClientYour ApolloClient instance. Useful for manually firing queries or writing data to the cache.
calledbooleanA boolean indicating if the query function has been called, used by useLazyQuery (not set for useQuery / Query).

useLazyQuery

Example

import { useLazyQuery } from "@apollo/react-hooks";
import gql from "graphql-tag";
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>;
}

Refer to the

section for a more in-depth overview of useLazyQuery.

Function Signature

function useLazyQuery<TData = any, TVariables = OperationVariables>(
query: DocumentNode,
options?: LazyQueryHookOptions<TData, TVariables>,
): [
(options?: QueryLazyOptions<TVariables>) => void,
QueryResult<TData, TVariables>
] {}

Params

query

ParamTypeDescription
queryDocumentNodeA GraphQL query document parsed into an AST by graphql-tag.

options

OptionTypeDescription
queryDocumentNodeA 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
pollIntervalnumberSpecifies the interval in ms at which you want your component to poll for data. Defaults to 0 (no polling).
notifyOnNetworkStatusChangebooleanWhether updates to the network status or network error should re-render your component. Defaults to false.
fetchPolicyFetchPolicyHow you want your component to interact with the Apollo cache. Defaults to "cache-first".
errorPolicyErrorPolicyHow you want your component to handle network and GraphQL errors. Defaults to "none", which means we treat GraphQL errors as runtime errors.
ssrbooleanPass in false to skip your query during server-side rendering.
displayNamestringThe name of your component to be displayed in React DevTools. Defaults to 'Query'.
skipbooleanIf skip is true, the query will be skipped entirely. Not available with useLazyQuery.
onCompleted(data: TData | {}) => voidA callback executed once your query successfully completes.
onError(error: ApolloError) => voidA callback executed in the event of an error.
contextRecord<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.
partialRefetchbooleanIf 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.
clientApolloClientAn ApolloClient instance. By default useQuery / Query uses the client passed down via context, but a different client can be passed in.
returnPartialDatabooleanOpt into receiving partial results from the cache for queries that are not fully satisfied by the cache. false by default.

Result

Execute function

ParamTypeDescription
Execute functionoptions?: QueryLazyOptions<TVariables>) => voidFunction that can be triggered to execute the suspended query. After being called, useLazyQuery behaves just like useQuery.

Result object

PropertyTypeDescription
dataTDataAn object containing the result of your GraphQL query. Defaults to undefined.
loadingbooleanA boolean that indicates whether the request is in flight
errorApolloErrorA runtime error with graphQLErrors and networkError properties
variables{ [key: string]: any }An object containing the variables the query was called with
networkStatusNetworkStatusA 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) => voidThis function sets up an interval in ms and fetches the query each time the specified interval passes.
stopPolling() => voidThis function stops the query from polling.
subscribeToMore(options: { document: DocumentNode, variables?: TVariables, updateQuery?: Function, onError?: Function}) => () => voidA function that sets up a
subscription
. subscribeToMore returns a function that you can use to unsubscribe.
updateQuery(previousResult: TData, options: { variables: TVariables }) => TDataA function that allows you to update the query's result in the cache outside the context of a fetch, mutation, or subscription
clientApolloClientYour ApolloClient instance. Useful for manually firing queries or writing data to the cache.
calledbooleanA boolean indicating if the query function has been called, used by useLazyQuery (not set for useQuery / Query).

useMutation

Example

import { useMutation } from '@apollo/react-hooks';
import gql from 'graphql-tag';
const ADD_TODO = gql`
mutation AddTodo($type: String!) {
addTodo(type: $type) {
id
type
}
}
`;
function AddTodo() {
let input;
const [addTodo, { data }] = useMutation(ADD_TODO);
return (
<div>
<form
onSubmit={e => {
e.preventDefault();
addTodo({ variables: { type: input.value } });
input.value = '';
}}
>
<input
ref={node => {
input = node;
}}
/>
<button type="submit">Add Todo</button>
</form>
</div>
);
}

Refer to the

section for a more in-depth overview of useMutation.

Function Signature

function useMutation<TData = any, TVariables = OperationVariables>(
mutation: DocumentNode,
options?: MutationHookOptions<TData, TVariables>,
): MutationTuple<TData, TVariables> {}

Params

mutation

ParamTypeDescription
mutationDocumentNodeA GraphQL mutation document parsed into an AST by graphql-tag.

options

OptionTypeDescription
mutationDocumentNodeA 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
ignoreResultsbooleanIf true, the returned data property will not update with the mutation result.
optimisticResponseObjectProvide a
mutation response
before the result comes back from the server
refetchQueriesArray<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.
awaitRefetchQueriesbooleanQueries 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) => voidA callback executed once your mutation successfully completes
onError(error: ApolloError) => voidA callback executed in the event of an error.
contextRecord<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.
clientApolloClientAn ApolloClient instance. By default useMutation / Mutation uses the client passed down via context, but a different client can be passed in.

Result

Mutate function:

PropertyTypeDescription
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:

PropertyTypeDescription
dataTDataThe data returned from your mutation. It can be undefined if ignoreResults is true.
loadingbooleanA boolean indicating whether your mutation is in flight
errorApolloErrorAny errors returned from the mutation
calledbooleanA boolean indicating if the mutate function has been called
clientApolloClientYour ApolloClient instance. Useful for invoking cache methods outside the context of the update function, such as client.writeData and client.readQuery.

useSubscription

Example

const COMMENTS_SUBSCRIPTION = gql`
subscription onCommentAdded($repoFullName: String!) {
commentAdded(repoFullName: $repoFullName) {
id
content
}
}
`;
function DontReadTheComments({ repoFullName }) {
const {
data: { commentAdded },
loading,
} = useSubscription(COMMENTS_SUBSCRIPTION, { variables: { repoFullName } });
return <h4>New comment: {!loading && commentAdded.content}</h4>;
}

Refer to the

section for a more in-depth overview of useSubscription.

Function Signature

function useSubscription<TData = any, TVariables = OperationVariables>(
subscription: DocumentNode,
options?: SubscriptionHookOptions<TData, TVariables>,
): {
variables: TVariables;
loading: boolean;
data?: TData;
error?: ApolloError;
} {}

Params

subscription

ParamTypeDescription
subscriptionDocumentNodeA GraphQL subscription document parsed into an AST by graphql-tag.

options

OptionTypeDescription
subscriptionDocumentNodeA 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
shouldResubscribebooleanDetermines if your subscription should be unsubscribed and subscribed again
skipbooleanIf skip is true, the subscription will be skipped entirely
onSubscriptionData(options: OnSubscriptionDataOptions<TData>) => anyAllows 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.
fetchPolicyFetchPolicyHow you want your component to interact with the Apollo cache. Defaults to "cache-first".
clientApolloClientAn ApolloClient instance. By default useSubscription / Subscription uses the client passed down via context, but a different client can be passed in.

Result

PropertyTypeDescription
dataTDataAn object containing the result of your GraphQL subscription. Defaults to an empty object.
loadingbooleanA boolean that indicates whether any initial data has been returned
errorApolloErrorA runtime error with graphQLErrors and networkError properties

useApolloClient

Example

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`)
}

Function Signature

function useApolloClient(): ApolloClient<object> {}

Result

ParamTypeDescription
Apollo Client instanceApolloClient<object>The ApolloClient instance being used by the application.

ApolloProvider

The ApolloProvider component leverages

to make a configured instance available throughout a React component tree. This component can be imported directly from the @apollo/react-common package where it lives, or from one of the @apollo/react-hooks, @apollo/react-components, and @apollo/react-hoc packages.

import { ApolloProvider } from '@apollo/react-hooks';

Props

OptionTypeDescription
clientApolloClient<TCache>An ApolloClient instance.

Example

ReactDOM.render(
<ApolloProvider client={client}>
<MyRootComponent />
</ApolloProvider>,
document.getElementById('root'),
);
Previous
class ApolloClient
Next
@apollo/react-ssr
Edit on GitHubEditForumsDiscord

© 2024 Apollo Graph Inc.

Privacy Policy

Company