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) {
      firstName
      lastName
      online
      id
    }
  }
`;
 
// 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)