如何重置 Apollo Client 的 useMutation 钩子

How do I reset the useMutation hook of Apollo Client

我正在开发一个使用 useMutation of Apollo Client 绑定到 GraphQL 突变的 React 表单。在服务器上,我执行一些验证,如果出现错误,我将拒绝更改。在客户端,我使用 error 对象来接收验证错误。我的钩子看起来像这样:

const [addDrone, { error }] = useMutation(ADD_DRONE)

所以我解压缩 error 对象并在对话框中将其呈现给用户,让 him/her 知道哪里出了问题。用户关闭对话框后,我想给用户一个机会来修复错误,以便 he/she 可以重新提交表单。这是事情变得毛茸茸的地方。我想在用户关闭对话框时清除 error 对象,但由于此变量来自 useMutation 挂钩,因此我无法更改或重置它。看起来 useMutation 被设计为只能触发一次,不能再次使用。

所以我的问题是,有没有办法将 useMutation 挂钩“重置”回其原始状态?

更新 12/22/2021:从 @apollo/client 的版本 3.5.0 开始,useMutation 挂钩现在提供 reset 方法。您可以使用此方法将挂钩重置回其初始状态。例如:

const [addDrone, { error, reset }] = useMutation(ADD_DRONE)

以下是 the official documentation on this method 的一些注释。

Call reset to reset the mutation's result to its initial state (i.e., before the mutate function was called). You can use this to enable users to dismiss mutation result data or errors in the UI.

Calling reset does not remove any cached data returned by the mutation's execution. It only affects the state associated with the useMutation hook, causing the corresponding component to rerender.


旧答案,为使用旧版本 @apollo/client 的人保留:

截至 2020 年 12 月 26 日,无法重置 useMutation,但是 Apollo 功能请求回购中有两个功能请求 #157 #170 要求一个,因此这可能会在未来。

现在实现此行为的最简单方法是删除 error 变量并改用 onError 处理程序。这是 useMutation 提供的回调,它使用相同的 error 对象。然后,您可以将其连接到您自己的有状态变量,这为您提供了完全相同的 error 变量 使用 setError 清除它的能力。请参阅下面的示例:

  const [error, setError] = React.useState(null)
  const [addDrone] = useMutation(ADD_DRONE, {
    onError: setError,
  })

如果您还想重置 data 对象,您可以引入另一个有状态元组 [data, setData] 并将 setData 连接到 onCompleted 回调。