通过compose()使用的graphQL变异的回调

时间:2017-11-07 06:36:03

标签: javascript callback graphql

如何进行GraphQL变异回调?

这就是我的反应成分和突变的样子:

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)

1 个答案:

答案 0 :(得分:4)

我建议你使用变异作为承诺,当点击表格提交时,你提出请求。

请注意,可以在.catch函数中检索登录错误。该错误包含最终网络或graphql错误,需要区别对待。请参阅示例this post

组件可能如下所示:



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)