简体   繁体   English

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

[英]Callback for graphQL mutation which is used via compose()

How do I do a GraphQL mutation callback? 如何进行GraphQL突变回调?

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)

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. 请注意,可以在.catch函数中检索登录错误。 The error consists of an eventual network or graphql Error which need to be treated differently. 该错误由最终的网络或graphql错误组成,需要区别对待。 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 eg 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) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM