w3resource

@apollo/react-hooks


This tutorial outlines some of the @apollo/react-hooks API reference

Installation

npm install @apollo/react-hooks

useQuery

The code snippet below demonstrates how to use the useQuery package of the @apollo/react-hooks

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>;
}

Function Signature

function useQuery<TData = any, TVariables = OperationVariables>(
  query: DocumentNode,
  options?: QueryHookOptions<TData, TVariables>,
): 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).
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 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).

Previous: Authentication
Next: @apollo/react-ssr



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/apollo-graphql/apollo-react-hooks.php