简体   繁体   English

如何使用自定义类型创建 apollo 客户端查询

[英]how to create apollo client query with custom types

I have to do a query and I have to pass a nested variable.我必须做一个查询,我必须传递一个嵌套变量。 Below is the working query when I use apollo graphql client interface.下面是我使用 apollo graphql 客户端界面时的工作查询。 It is giving me expected result.它给了我预期的结果。 Below is the working query以下是工作查询

query($input: MyProductInput!){
  MyProductCategories(input: $input){
    id,
    name
  }
}

Variable which i am passing我正在传递的变量

{
  "input": {
    "locale": "ENG"
  }
}

MyProductInput type look like this at SERVER MyProductInput类型在 SERVER 上看起来像这样

type MyProductInput {
  locale: Locale!
}
enum Locale {
  IND
  AUS
  ENG
}

when I try to call the same query from my React App, it is giving me error, It says 400 bad request.当我尝试从我的 React 应用程序调用相同的查询时,它给我错误,它说 400 错误请求。 My React query look like this.我的 React 查询看起来像这样。

const PRODUCT_LIST = gql`
  query ($locale: String!) {
    MyProductCategories(input: {locale: $locale}){
      id,
      name
    }
  }
`;

const { loading, error, data } = useQuery(PRODUCT_LIST, {
  variables: {
    "input": {
      "locale": "ENG"
    }
  },
});

How can i convert my react query to accommodate custom types??我如何转换我的反应查询以适应自定义类型?

Note : I am using JavaScipt not Typescript at Front-end side注意:我在前端使用 JavaScipt 而不是 Typescript

I got the answer.我得到了答案。 I just had to do this $input: MyProductInput!我只需要执行$input: MyProductInput! within query and pass $input to MyProductCategories .在查询中并将$input传递给MyProductCategories Below is working example.下面是工作示例。

const PRODUCT_LIST = gql`
  query ($input: MyProductInput!) {
    MyProductCategories(input: $input){
      id,
      name
    }
  }
`;

React Query using hooks使用钩子响应查询

const { loading, error, data } = useQuery(PRODUCT_LIST, {
  variables: {
    "input": {
      "locale": "ENG"
    }
  },
});

No need to worry about custom types as it is already there at server.无需担心自定义类型,因为它已经存在于服务器中。 Just pass is as it is and set the variables只需按原样传递并设置变量

Take a look in the docs:看看文档:

https://www.apollographql.com/docs/react/api/react/hooks/ https://www.apollographql.com/docs/react/api/react/hooks/

And can you see more information about the error message you get back?您能否查看有关您返回的错误消息的更多信息?

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

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