【问题标题】:GraphQL refetchQueries after mutation, this.props not updatedGraphQL refetchQueries 突变后,this.props 未更新
【发布时间】:2019-03-10 17:32:04
【问题描述】:

这个问题对我来说毫无意义......我正在使用这样的突变将作者添加到数据库中:

this.props
      .addAuthorMutation({
        variables: {
          name: this.state.name,
          age: this.state.age
        },
        refetchQueries: [
          {
            query: getAuthorsQuery,
            variables: {
              awaitRefetchQueries: true
            }
          }
        ]
      })
      .then(() => this.submitBookAlso());

那么简单...

  submitBookAlso() {
    console.log(this);
    console.log(this.props);
  }

由于某种神秘的原因,当我在控制台中检查 (this) 时,this.props.getAuthorsQuery.authors 包含我添加的作者,但是,控制台中的 (this.props) 没有。新作者已成功添加到另一个组件的下拉列表中,并且在数据库中,但是在突变后我似乎无法获取作者。我想过滤一下...

let author = this.props.getAuthorsQuery.authors.filter(
  author => this.state.name === author.name
);
console.log(author);

...但这只是给了我一个空数组。我想要做的是在完成时触发另一个突变(将一本书添加到单独的数据库集合中,新添加的作者是作者)。

我在不使用 awaitRefetchQueries 以及使用 onCompleted 而不是 .then() 的情况下得到了相同的结果。这些是我当前的依赖项:

  "dependencies": {
    "apollo-boost": "^0.1.16",
    "graphql": "^14.0.2",
    "react": "^16.5.2",
    "react-apollo": "^2.2.4",
    "react-dom": "^16.5.2",
    "react-scripts": "2.0.3"
  },

谢谢!

【问题讨论】:

  • 更新:所以这看起来是 Apollo 设计的问题,并且 refetchQueries 方法在运行 .then() 之前没有等待完成......显然这是设计使然,将是一个中断链改变它。与此同时,它可以像这样简单地链接承诺......this.props.myMutation( { variables: { myVariables } } ) .then( () => this.props.myQuery.refetch() ) .then( data => data.data.newQueryDataShouleBeUpdated )

标签: javascript reactjs graphql apollo react-apollo


【解决方案1】:

尝试将awaitRefetchQueries 直接传递给突变,而不是像这样嵌套在refetchQueries 中:

this.props
      .addAuthorMutation({
        variables: {
          name: this.state.name,
          age: this.state.age
        },
        awaitRefetchQueries: true,
        refetchQueries: [
          {
            query: getAuthorsQuery
          }
        ]
      })
      .then(() => this.submitBookAlso());

【讨论】:

    【解决方案2】:

    // 在 hooks 中声明 useQuery 示例时通过 Refetch

    const {data, error, loading, refetch} = useQuery("Your query")
    
    const [addAuthorMutation] = useMutation("Your Mutation",{
    variables: { "your variables"},
    onCompleted: (data) => { "dispatch your action creators"},
    refetch()
    
    })
    

    【讨论】:

      猜你喜欢
      • 2020-05-30
      • 2019-02-13
      • 2018-07-15
      • 2019-02-17
      • 2019-09-27
      • 2018-10-16
      • 2021-12-02
      • 2020-05-09
      • 2021-03-24
      相关资源
      最近更新 更多