【问题标题】:react query refetches before mutation are executed在执行突变之前反应查询重新获取
【发布时间】:2021-06-16 19:50:55
【问题描述】:

我开始使用 react 查询突变,但在查看网络请求时发现,当我调用突变时,它会在执行它之前先获取它。

这是我的突变

 const mutation= useMutation(
    async (values: VoteProps) => {
      await fetch("/api/test/test", {
        method: "POST",
        body: JSON.stringify(values),
        headers: {
          "Content-Type": "application/json",
        },
      });
    },
     onSettled: (data: any, error: any, variables: any, context: any) => {
      refetch();
    },
}

这是我的 useQuery

  const { isLoading, isError, data, error, refetch } = useQuery<test>(
    "test",
    test,
    { refetchInterval: 30000, refetchIntervalInBackground: true }
  );

突变改变了测试 useQuery 的值

是否有原因或禁用它的方法?

谢谢

【问题讨论】:

  • 它可能只是因为您聚焦窗口而无效。
  • @TkDodo 测试时我没有离开页面,并且我有 refetchIntervalInBackground 所以它每 30 秒重新获取一次,无论我是否关注焦点

标签: reactjs react-query


【解决方案1】:

在你的变异函数中返回 fetch 将解决问题。

说明

变异函数应该返回一个类似于 promise 的值。 useMutation 等到这个 Promise 被解决或被拒绝,然后调用 onSettled 回调。

你的变异函数是一个空函数,所以当你调用mutation.mutate()时会发生这种情况:

  1. useMutation 调用变异函数
  2. fetch()异步调用
  3. 变异函数立即返回undefined
  4. useMutation 调用 onSettled 回调,因为突变函数返回了一些东西。 (虽然fetch还没有解决)
  5. 查询被重新获取
  6. 突变和查询请求稍后会从服务器获得响应

【讨论】:

    猜你喜欢
    • 2021-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-20
    • 2021-09-10
    • 2020-06-08
    • 2021-01-18
    • 1970-01-01
    相关资源
    最近更新 更多