flutterdartgraphqlhasuraflutter-graphql

How to pass enum value in hasura query in flutter


So I am trying to query data from hasura but one of the variable that I am passing is a variable due to which it always gives some error I tried many different solutions like this but no solution so far this is the query

query MyQuery {
  Product(where: { product_category: { _eq: Liquor } }) {
    product_decription
    product_category
    product_id
    product_img
    product_name
    product_price
  }
}

and this is the query part that I am trying

QueryOptions query = QueryOptions(
  document: gql(r'''
    query MyQuery($category:[ProductType_enum!]) {
      Product(where: {
        product_category: {
          _eq: $category
        }
      }) {
        product_category
        product_decription
        product_id
        product_img
        product_name
        product_price
       }
    }
  '''),
  variables: <String, dynamic> {
    'category': ['Liquor']
  });

I am not able to understand what's wrong I am doing in this query this is the enum class

enum Product_type { Toiletries Liquor Household_Requisites General_Items Food_Medecine Watches_Stationery }

I am getting this error

OperationException (OperationException(linkException: null, graphqlErrors: [GraphQLError(message: variable "category" is declared as [ProductType_enum!], but used where ProductType_enum is expected, locations: null, path: null, extensions: {path: $.selectionSet.Product.args.where.product_category._eq, code: validation-failed})]))

for normal query it works fine.


Solution

  • The issue is that you're passing an array where a single value is expected. The important part of the error message is this:

    variable "category" is declared as [ProductType_enum!], but used where ProductType_enum is expected

    In this case [ProductType_enum!] represents an array but the _eq part of your query is expecting a single value.

    Just update your variables to be 'category': 'Liquor' and it should work for you.

    If you want to be able to pass an array you should use _in instead of _eq and then write your query as

    query MyQuery($categories:[ProductType_enum!]) {
     Product(where: {product_category: {_in: $categories}})