【问题标题】:How to handle multiple mutations in parallel with react-query如何与 react-query 并行处理多个突变
【发布时间】:2022-01-19 22:27:20
【问题描述】:

我有一个自定义的useMutation 钩子:

  const {
    status: updateScheduleStatus,
    reset: updateScheduleReset,
    mutateAsync: updateSchedule,
  } = useUpdateSchedule(queryClient, jobId as string);

据我所知设置了突变,但如果我想进行多个并行突变,我将如何使用它?

我已尝试实现以下内容,但突变在到达Promise.all(mutations 行之前执行。

        let mutations: Array<any> = [];

        schedulesForDeletion.forEach(async (schedule) => {
          const resp = await monitoringService?.getSchedule(
            schedule.schedule_id,
          );
          mutations.push(
            updateSchedule({
              monitoringService: monitoringService as MonitoringServiceClient,
              schedule,
              etag: resp?.type === "data" ? resp.headers.etag : "",
            }),
          );
        });

        console.dir(mutations);

        await Promise.all(mutations);

mutateAsync 返回一个Promise 时,我会经历它,它们不会按顺序触发,但似乎确实会触发。

有没有办法在react-query 中处理这个问题,或者我最好用 axios 执行这个?在react-query 中执行此操作会很有用,因为我需要在突变成功时使一些查询无效。

【问题讨论】:

    标签: javascript reactjs promise react-query promise.all


    【解决方案1】:

    并行运行多个突变确实适用于mutateAsync

    const { mutateAsync } = useMutation(num => Promise.resolve(num + 1))
    
    const promise1 = mutateAsync(1)
    const promise2 = mutateAsync(2)
    
    await Promise.all([promise1, promise2])
    

    我猜在您的示例中,您将 Promise 推送到数组,然后继续循环并 await monitoringService?.getSchedule。只有在返回之后,您才会触发第二个突变。

    所以从这个意义上说,这似乎是“阻止”你执行的原因。如果你推送来自getSchedule 的原始 Promise,它应该可以工作:

    schedulesForDeletion.forEach((schedule) => {
      mutations.push(
        monitoringService?.getSchedule(
          schedule.schedule_id,
          ).then(resp => updateSchedule({...})
        )
      )
    })
    

    【讨论】:

      猜你喜欢
      • 2021-05-31
      • 2020-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-09
      • 2021-11-05
      • 1970-01-01
      • 2017-01-27
      相关资源
      最近更新 更多