refetchQueries onComplete 回调

Tam*_*ock 5 react-native react-apollo

是否可以添加在 refetchQueries 完成时调用的回调函数?问题是我不希望在后台发生突变后重新获取,因为如果数据没有立即更新然后突然更新,这可能会使用户感到困惑。提交函数可能如下所示:

async submit(values) {
  this.setState({ submitting: true })
  validateUrl(values.url).then((response:Response) => {
    response.json().then((data) => {
      if (data.length > 0) {
        this.onError("Invalid url")
        this.setState({ submitting: false })
      } else {
        this.props.mutate({
          variables: values,
          refetchQueries: [{ query: LinksQuery}]
        }).then(() => {
          this.props.navigation.pop(2)
          this.props.navigation.state.params.showSuccessFeedback()
          this.setState({ submitting: false })
        });
      }
    });
  })
}
Run Code Online (Sandbox Code Playgroud)

但是我不想在 LinksQuery 的重新获取完成之前返回。

一种解决方案是使用 graphql() 装饰器将 Query 添加到组件,然后使用 refetch() 返回一个承诺。但是在 refetchQueries 选项中使用它会更干净。特别是如果应该重新获取多个查询。

react-apollo的版本是1.4.15,不过如果能解决问题我可能愿意升级到react-apollo 2.*

Anh*_*ham 6

根据文档,我们有awaitRefetchQueries

作为 refetchQueries 的一部分重新获取的查询是异步处理的,并且不会在突变完成(解决)之前等待。将此设置为 true 将确保在认为更改完成之前完成重新获取的查询。默认为假。

所以,你需要做的是在函数的对象内部设置awaitRefetchQueriesequal 。Truemutate

async submit(values) {
  this.setState({ submitting: true })
  validateUrl(values.url).then((response:Response) => {
    response.json().then((data) => {
      if (data.length > 0) {
        this.onError("Invalid url")
        this.setState({ submitting: false })
      } else {
        this.props.mutate({
          variables: values,
          refetchQueries: [{ query: LinksQuery}],
          awaitRefetchQueries: true
        }).then(() => {
          this.props.navigation.pop(2)
          this.props.navigation.state.params.showSuccessFeedback()
          this.setState({ submitting: false })
        });
      }
    });
  })
}
Run Code Online (Sandbox Code Playgroud)

我也刚刚提出了同样的问题,这对我有用。希望能帮助到你!