【问题标题】:Callback for graphQL mutation which is used via compose()通过 compose() 使用的 graphQL 突变的回调
【发布时间】:2018-04-19 11:19:02
【问题描述】:

如何进行 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)

【问题讨论】:

    标签: javascript callback graphql


    【解决方案1】:

    我建议您将突变用作承诺,并在单击表单提交时提出请求。

    请注意,可以在.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)

    【讨论】:

      猜你喜欢
      • 2018-11-11
      • 2020-02-18
      • 2022-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-10
      • 2018-06-20
      • 2017-01-21
      相关资源
      最近更新 更多