Search code examples
reactjsgraphqlredux-formgraphiql

Why are Results logging as undefined after a GraphQL Mutation?


In one of my components within a redux-form onSubmit, I have the following:

const result = await helloSignup(values);
console.log(result);

helloSignup is mutating the database as expected but the const result is currently be logged as undefined

Why?

My HOC/mutation helloSignup:

export const HELLO_SIGNUP_MUTATION = gql`
mutation (
  $email: String!
  $code: String!
) {
  signup(authProvider: {
    emailAndCode: {
      email: $email
      code: $code
    }
  }) {
    token
    user {
      id
    }
  }
}
`;

export default graphql(
  HELLO_SIGNUP_MUTATION,
  {
    props: ({ mutate }) => ({
      emailAndCodeSignup: async (variables) => {
        const { data } = await mutate({ variables });
        const { token } = data.signup;
      },
    }),
  }
);

Using GraphiQL, I can see that my graphql mutation, returns the desired results:

{
  "data": {
    "signup": {
      "token": "xxx",
      "user": {
        "id": "16"
      }
    }
  }
}

If GraphiQL is getting the desired results after mutating, why isn't the result being console logged above?


Solution

  • React-Apollo provides a HOC for client side queries and mutations called withApollo.

    This signature is something like this:

    withApollo(MyForm)
    

    https://www.apollographql.com/docs/react/basics/setup.html#withApollo

    which adds a prop of 'client' to the MyForm component. On form submission, you'd want to access this prop, and call the mutation from there. So in your form submit handler youd end up with something like this:

    https://www.apollographql.com/docs/react/basics/mutations.html#basics

    onSubmit() {
      const { client } = this.props
      const options = {} // your mutation options
      // mutations ands queries return promises, 
      // so you must wait for their completion before accessing data
      client.mutate(
        HELLO_SIGNUP_MUTATION, 
        options
       ).then(({ data }) => (
         console.log('got data', data);
       )
      }
    }
    

    Where data should be whats coming back from the API