useQuery and useMutation Hooks
Fetch data with useQuery, execute mutations with useMutation, and handle loading, error, and data states.
Defining a Query with gql
The gql template tag from @apollo/client parses a GraphQL query string into a DocumentNode at module load time. Define queries outside components: const GET_USERS = gql`query GetUsers { users { id name email } }`.
Note: in production code, use single-quoted strings wrapped by gql as a tagged template. The gql tag accepts a template literal syntax in JavaScript source.
useQuery Return Values
useQuery(GET_USERS) returns { loading, error, data, refetch, fetchMore, networkStatus }. loading is true during the initial fetch. error contains any GraphQL or network errors. data contains the query result matching the query shape.
Check loading and error first before accessing data to avoid rendering null values.
All lessons in this course
- GraphQL Fundamentals for React Developers
- Setting Up Apollo Client in React
- useQuery and useMutation Hooks
- Apollo Cache: Normalization and Updates