【问题标题】:How to make a query and a mutation in the same time with GraphQL?如何使用 GraphQL 同时进行查询和突变?
【发布时间】:2019-04-04 20:40:13
【问题描述】:

大家好,我是 Apollo - GraphQL 的新手,我正在使用我的 React Native 应用程序来实现我的服务器。

当我尝试构建密码更改功能时,我收到以下错误this.props.resetPassword is not a function. (In 'this.props.resetPassword(_id, password)', 'this.props.resetPassword' is undefined)

我的代码是这样的

toSend() {
    const { _id } = this.props.data.me;
    const { password } = this.state;
    console.log(_id, password)
    this.props
        .resetPassword(_id, password)
        .then(({ data }) => {
            return console.log(data);
        })
}

这是我的查询和我的突变

export default graphql(
    gql`
    query me {
      me {
        _id
      }
    }
  `,
    gql`
    mutation resetPassword($_id: String!, $password: String!) {
      resetPassword(_id: $_id, password: $password) {
        _id
      }
    }
  `,
    {
        props: ({ mutate }) => ({
            resetPassword: (_id, password) => mutate({ variables: { _id, password } }),
        }),
    },
)(PasswordChange);

【问题讨论】:

    标签: reactjs react-native graphql


    【解决方案1】:

    如果您使用的是graphql HOC,则需要使用compose 来组合多个查询/突变。例如:

    const mutationConfig = {
      props: ({mutate, ownProps}) => ({
        resetPassword: (_id, password) => mutate({ variables: { _id, password } }),
        ...ownProps,
      })
    }
    
    export default compose(
      graphql(YOUR_QUERY, { name: 'createTodo' }),
      graphql(YOUR_MUTATION, mutationConfig),
    )(MyComponent);
    

    请记住,HOC 将默认传递它收到的任何道具,但如果您在配置中为 props 提供函数,则您可以使用 ownProps 来执行此操作。此外,当使用compose 时,如果 HOC 中的任何一个依赖于其他的 props,则 HOC 的顺序很重要。这意味着只要您的查询首先出现在 compose 中,您就可以在突变配置中使用查询 HOC 的 data

    【讨论】:

      猜你喜欢
      • 2021-02-17
      • 2022-11-25
      • 2021-03-16
      • 2021-09-09
      • 2018-02-19
      • 2020-11-04
      • 2017-09-23
      • 2017-08-24
      • 2015-11-27
      相关资源
      最近更新 更多