1

How do I do a GraphQL mutation callback?

This is how my react component and the mutation looks like:

class CreateAccount extends Component {
  constructor () {
    super()
    this.state = {
      username: '',
      password: ''
    }
  }

  render () {
    return (
      // form with input fields; values get stored as state
    )
  }

  _createUser = async () => {
    const { username, password } = this.state
    await this.props.createUserMutation({
      variables: {
        username,
        password
      }
    })
  }
}

export default compose(
  withData,
  withApollo,
  graphql(
    gql`
      mutation RootMutationQuery($username: String!, $password: String!) {
        createUser(
          username: $username,
          password: $password,
        ) {
          _id
          username
          password
        }
      }
    `, { name: 'createUserMutation' }
  )
)(CreateAccount)
user3142695
  • 15,844
  • 47
  • 176
  • 332

1 Answers1

4

I would suggest you use the mutation as promise and when clicking the form submit you make the request.

Be aware that a login error can be retrieved in the .catch function. The error consists of an eventual network or graphql Error which need to be treated differently. See for example this post.

The Component could look like this:

class CreateAccount extends Component {
  constructor(props) {
    super(props);
    this.state = {
      username: '',
      password: ''
    };
  }

  render() {
    return (
      // form with input fields; values get stored as state
      // on submit is handled for the form
    );
  }

  _onSubmit = (event) => {
    event.preventDefault();
    const { username, password } = this.state;
    
    this.props.createUserMutation({
      variables: { username, password }
    }).then(response => {
      // data in response.data.createUser
      // set state e.g. handle login
    }).catch(error => {
      // handle error
    });
  }
}

export default compose(
  graphql(
    gql `
      mutation RootMutationQuery($username: String!, $password: String!) {
        createUser(
          username: $username,
          password: $password,
        ) {
          _id
          username
          password
        }
      }
    `, {
      name: 'createUserMutation'
    }
  )
)(CreateAccount)
Locco0_0
  • 3,420
  • 5
  • 30
  • 42