useMutation返回的突变函数不传递变量



我正试图使用useMutation钩子返回的突变函数来创建用户(稍后我还必须进行登录突变(,但createUser((函数上传递的变量没有被传递。

这是我的注册表格代码:

import './SignUpForm.scss'
import { loader } from 'graphql.macro'
import { useMutation } from '@apollo/client'
import { useState } from 'react'
const CREATE_USER_MUTATION = loader('../../graphql/signup.graphql')
export default function SignUpForm(props) {
const [createUser, { data, loading, error }] = useMutation(CREATE_USER_MUTATION)
const [formState, setFormState] = useState({
firstName: undefined,
lastName: undefined,
email: undefined,
username: undefined,
password: undefined
})
const setAttr = (attr, e) => setFormState({ ...formState, [attr]: e.target.value })
return (
<>
<form className='signUpForm' onSubmit={async (e) => {
e.preventDefault();
await createUser({ variables: { data: formState } })
}}>
<h2>Member registration</h2>
<input placeholder='First name' autoComplete='on' id='firstNameInputField' onChange={ (e) => setAttr('firstName', e) }/>
<input placeholder='Last name' autoComplete='on' id='lastNameInputField' onChange={ (e) => setAttr('lastName', e) }/>
<input placeholder='Email' autoComplete='on' id='emailInputField' onChange={ (e) => setAttr('email', e) } />
<input placeholder='Username' autoComplete='on' id='usernameInputField' onChange={ (e) => setAttr('username', e) }/>
<input placeholder='Password' type='password' id='passwordInputField' onChange={ (e) => setAttr('password', e) }/>
<input type='submit' id='submitRegistrationButton'/>
</form>
<a href='/auth/signin'>Do you already have an account?</a>
</>
)
}

这是包含loader((函数正在加载的突变的.graphql文件:

mutation signup($SignupInput: SignupInput!) {
signup(data: $SignupInput) {
user {
username
} 
}
}

这是我的模式:

extend type Mutation {
signup(data: SignupInput!): AuthenticationResult!
}
extend type Query {
currentUser: User
}
type User {
id: ID!
email: String!
firstName: String!
lastName: String!
username: String!
salt: String!
password: String!
}
input SignupInput {
email: String!
firstName: String!
lastName: String!
username: String!
password: String!
}
type AuthenticationResult {
user: User
jwt: String
authError: String
}

在我的GraphQL服务器沙箱上运行这个突变也非常完美:

mutation CreateUserTest($SignupInput: SignupInput!) {
signup(data: $SignupInput) {
user {
username
} 
}
}

改变";数据";在变量对象声明为"时;SignupInput";没有起作用。

这是我在DevTools:的网络选项卡上找到的响应

{operationName: "signup", variables: {},…}
operationName: "signup"
query: "mutation signup($SignupInput: SignupInput!) {n  signup(data: $SignupInput) {n    user {n      usernamen      __typenamen    }n    __typenamen  }n}n"
variables: {}

我做错了什么?

您可能弄错了参数:

const CREATE_USER_MUTATION = loader('../../graphql/signup.graphql')
mutation signup($SignupInput: SignupInput!) { // <- notice the parameter takes a "SignupInput"
signup(data: $SignupInput) {
user {
username
} 
}
}

所以改变这个:

await createUser({ variables: { data: formState }})

至:

await createUser({ variables: { SignupInput: formState }})

参考:useMutuation钩子官方示例

最新更新