DEV Community 👩‍💻👨‍💻

Max Frolov
Max Frolov

Posted on

React Hook around Apollo GraphQL query

Here is an example of the custom hook around Apollo query, with simple reuse and keeping things in one place.
BTW you can check React Hook around Apollo GraphQL mutation here.

import * as RH from "@apollo/react-hooks";
import gql from "graphql-tag";
// users query
export const USERS_LIST_QUERY = gql`
  query GetUsersQuery($input: UsersInput) {
    getUsers(input: $input) {
// query entity hook
export const useUsersQuery = (variables = {}) => {
  const { data, loading, error } = RH.useQuery(USERS_LIST_QUERY, {
    variables: { input: { online: false, ...variables } }
  return {
    users: data?.getUsers || [], // list with default value
    isLoading: loading, // loading state
    error: error?.graphQLErrors, // parse errors here
    refetchUsers: data.refetch // refetch your query

More tips and best practices on my twitter.

Feedback is appreciated. Cheers!

Top comments (0)


11 Tips That Make You a Better Typescript Programmer

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields


Read the whole post now!