Search code examples
reactjsgraphqlapollo-client

Problem with passing data to graphql from react


I have username and password which I want to send to graphql backend from react on frontend. I'm using apollo client for that

on my client side I have this

const REGISTER_USER = gql`
  mutation RegisterUser($username: String!, $password: String!) {
    registerUser(username: $username, password: $password) {
      username,
      password
    }
  }
`;

And I'm calling it like this

registerUser({ variables: { username: values.username, password: values.password } })

On my server

const UserType = new GraphQLObjectType({
    name: 'user',
    fields: () => ({
        username: { type: GraphQLString },
        password: { type: GraphQLString }
    })
});
const Mutations = new GraphQLObjectType({
    name: 'Mutation',
    fields: {
        registerUser: {
            type: UserType,
            args: {
                username: { type: GraphQLString },
                password: { type: GraphQLString }
            },
            resolve(username, password) {
                console.log(username, password, 123)
            }
        },
    }
})

The problem is - I'm passing password and username separatly as strings, but my console.log(username, password, 123) in mutations gives back undefined and full object with username, password fields.

I'm not sure where I'm doing something wrong. All the help will be much appreciated.


Solution

  • The resolve function has source, args, context and info as params. You can read more about it in resolver function signature.

    So basically you're asking for source and args, that is why one is undefined and the other is the object of arguments. The way to get your variables in your resolver is:

    const Mutations = new GraphQLObjectType({
        name: 'Mutation',
        fields: {
            registerUser: {
                type: UserType,
                args: {
                    username: { type: GraphQLString },
                    password: { type: GraphQLString }
                },
                resolve: (source, args) {
                    console.log(args.username, args.password)
                    // HERE: you can access your arguments input as part of the 'args' object
                }
            },
        }
    })