简体   繁体   English

如何在 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.我可以在开发工具的 Apollo Explorer 中实现这一点,但我似乎无法将其转化为代码。

The following works in Apollo explorer: 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.但是,我不确定这如何转换为使用 useQuery 挂钩的代码。

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?我在这里错过了什么?

Your names are not correct你的名字不正确

Here you say filter will use the variable type在这里你说过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在这里你通过filter

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

You can你可以

First solution第一个解决方案

replace $type by $filter$filter替换$type

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

Second solution第二种解决方案

rename the variable filter to type将变量filter器重命名为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我让你选择,但第一个选项似乎是最好的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM