Search code examples
graphqlapolloreact-apollo

How to implement a filter on a query in Apollo?


I'm attempting to filter a query by a specific field. I can achieve this in Apollo explorer in dev tools but I can't seem to translate this into code.

The following works in Apollo explorer:

query ListUsersByType($filter: TableUsersFilterInput) {
  listUsers(filter: $filter) {
    items {
      email
      id
      type
    }
  }
}
{
  "filter": {
    "type": {
      "eq": "ADMIN"
    }
  }
}

I am unsure how this translates to the code using the useQuery hook however.

When I try the following it doesn't filter the list at all, it just fetches all of them regardless of type:

const ListUsersByType = gql`
  query ListUsersByType($type: TableUsersFilterInput) {
    listUsers(filter: $type) {
      items {
        email
        id
        type
      }
    }
  }
`
  const { data, loading, error } = useQuery(ListUsersByType, {
    variables: {
      filter: {
        type: {
          eq: 'ADMIN',
        },
      },
    },
  })

What am I missing here?


Solution

  • Your names are not correct

    Here you say filter will use the variable type

    const ListUsersByType = gql`
      query ListUsersByType($type: TableUsersFilterInput) {
        listUsers(filter: $type) {
          items {
            email
            id
            type
          }
        }
      }
    `
    

    And here you pass filter

      const { data, loading, error } = useQuery(ListUsersByType, {
        variables: {
          filter: {
            type: {
              eq: 'ADMIN',
            },
          },
        },
      })
    

    You can

    First solution

    replace $type by $filter

    const ListUsersByType = gql`
      query ListUsersByType($filter: TableUsersFilterInput) {
        listUsers(filter: $filter) {
          items {
            email
            id
            type
          }
        }
      }
    `
    

    Second solution

    rename the variable filter to type

      const { data, loading, error } = useQuery(ListUsersByType, {
        variables: {
          type: {
            type: {
              eq: 'ADMIN',
            },
          },
        },
      })
    

    My opinion

    I let you choose but the first option seems the best