【问题标题】:correct way to call GraphQL mutation from react using hooks使用钩子从反应中调用 GraphQL 突变的正确方法
【发布时间】:2020-12-12 00:04:54
【问题描述】:

我已经定义了以下突变和输入类型:

extend type Mutation {

    signup(input: SignupReq!): SignupStatus!

}

input SignupReq {
    email: String!
    password: String!
}

使用 graphql 游乐场:

mutation signup{signup(input:{password:"blabla", email: "my@email.dk"}){success, message}}

它返回:

{
  "data": {
    "signup": {
      "success": true,
      "message": "Success!"
    }
  }
}

这是我所期望的。

但是如何从我的 React 客户端调用这个突变?

我现在拥有的是:

const SIGNUP_MUTATION = gql`
  mutation SignupUser($input: SignupReq!) {
    signup(signupReq: $input) {success, message, token}
  }
`

  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')


const [signup, { data, loading, error }] = useMutation(SIGNUP_MUTATION)


const { data, loading, error } = await signup({ variables: { email, password } })


这几乎是标准的。

但我错过了一些我无法确定的东西。因为运行 React 脚本给了我以下错误信息:

'Field "signup" argument "input" of type "SignupReq!" is required, but it was not provided.',

如何从 react 中正确调用 Graphql。我一直找不到任何关于如何使用输入类型进行 React 突变的文档。

欢迎任何帮助。

【问题讨论】:

标签: reactjs graphql mutation


【解决方案1】:

您将emailpassword 作为变量传递到您的突变中:

variables: { email, password }

相反,正如您从突变中看到的那样,您必须传入一个 input 变量:

variables: {
  input: {
    email,
    password
  }
}

这会起作用,因为它会反映您的 GraphQL 架构中使用的类型:

input SignupReq {
  email: String!
  password: String!
}

【讨论】:

    猜你喜欢
    • 2020-11-11
    • 1970-01-01
    • 2020-03-20
    • 2020-08-15
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 2020-09-07
    • 2017-01-21
    相关资源
    最近更新 更多