使用 React 查询对两个不同的 API 实现多个突变

问题描述 投票:0回答:1
const first = useMutation({
    mutationFn: (data) => {
      return Promise.all([
        (axios.put(
          "https://dummyjson.com/products/1",
          JSON.stringify({
            title: "iPhone Galaxy +1",
          })
        ),
        axios.post(
          "https://reqres.in/api/users",
          JSON.stringify({
            name: "morpheus",
            job: "leader",
          })
        )),
      ]);
    },
    onSuccess: (data) => {
      console.log(data);
    },

    onError: (error) => {
      console.log(error);
    },
  });


实际上我想对两个不同的 api 执行两个 post 请求,但 useMutation 仅发布到一个 api

在上面的代码中,只有第二个承诺得到解决,第一个承诺没有得到解决


预期输出: 两个 Promise 都应该得到解决并给出两个 api 的响应

javascript axios es6-promise react-query
1个回答
0
投票

您的代码似乎有错字。

const array = [(a, b)]

这会生成一个数组

[b]
,因为
,
运算符返回右侧的项目。
[(a, b)]
[a, b]
不同,括号确实有含义。如果你检查你的代码,你会发现那里有括号

[
    (
        axios.put(),
        axios.post()
    ),
]

我删除了

put
post
的参数来演示。您应该观察两个网络请求,但您只等待 POST 一个,因为您正在执行以下操作:

axios.get() // runs, but result is not used
const responses = Promise.all([axion.post()]) // only the post is consumed
© www.soinside.com 2019 - 2024. All rights reserved.