Search code examples
reactjsgraphqlmutation

correct way to call GraphQL mutation from react using hooks


I have defined the following mutation and inputtype:

extend type Mutation {

    signup(input: SignupReq!): SignupStatus!

}

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

using graphql playground:

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

it returns:

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

which is what I expect.

but how do I call this mutation from my React client?

what I have now is:

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 } })


which is pretty much standard.

but I'm missing something I just cant pinpoint. Cause running the React script gives me the following error message:

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

How do I make the correct call to Graphql from react. I have been unable to find any documentation on how to use input types for mutations from React.

any help welcome.

Kim


Solution

  • You are passing in email and password as variables into your mutation:

    variables: { email, password }
    

    Instead, as you can see from your mutation, you have to pass in an input variable:

    variables: {
      input: {
        email,
        password
      }
    }
    

    This will work, as it then mirrors the type used in your GraphQL schema:

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