React:如何根据每个已解决的承诺发送多个发布请求,并在所有请求解决后发送所有已解决的数据

问题描述 投票:0回答:1

我想一键发送多个帖子请求。每个帖子请求都会在前一个请求得到解决后发送(无论它是对是错)。然后我需要收集数组中所有已解析的响应,最后发送该数组。 注意:我正在使用 React Query。 如果有点令人困惑,我已经添加了代码以及代码sandboxhttps://codesandbox.io/s/flamboyant-banzai-cgthsh?file=/src/App.js

// to save the responses
 const [saveTodo, setSaveTodo] = useState([]);

const { mutateAsync } = useMutation({
    mutationFn: (data) => {
      return axios.post("https://jsonplaceholder.typicode.com/posts", data);
    },
    onSuccess: (data) => {
     setSaveTodo((saveTodo) => [...saveTodo, data.data.post]);
    },
  });


// I want to send this request with all resolved responses after all requests are resolved
 const nextMutation = useMutation({
    mutationFn: (data) => {
      return axios.post("https://jsonplaceholder.typicode.com/posts", data);
    }
  });



// this function runs on loop until the array length is reached
  const postUrlSubmit = async (urls, idx) => {
    const url = urls[idx];

    await mutateAsync(url, {
      onSettled: () => {
        const next = urls?.[idx + 1];
        if (next) {
          postUrlSubmit(urls, idx + 1);
        }else {

          // if next is finished and then all response from the state must send to the server
          /**
           * here the problem comes in.
           * the next mutatin invokes with empty array
           * if you see the console log, you will seee that savetodo array is 0
           */
              nextMutation.mutate(saveTodo)
      },
    });
  };

const handleSubmit = async() => {
  await postUrlSubmit(["Todo 1", "Todo 2", "Todo 3"], 0);
}

return(
<button onClick={handleSubmit}>submit</button>
)

javascript reactjs http-post tanstackreact-query
1个回答
0
投票

我已经解决了这个问题。感谢戴夫·格雷。他的解释非常清楚。我遵循了他的解决方案,效果非常好。

const handleInput = async () => {                                           
const saveData = []; 
const array =  ["Todo 1", "Todo 2", "Todo 3"]                
array.reduce(async (acc, url, idx) => {

// awaits for the previous item to complete
await acc;

//get the next item;
const response = await mutation.mutateAsync(url);
//saving the responses in the array
saveData.push(response.data.post);

// last step: all request finished and check lenght of both array
if (array.length - 1 === idx && saveData.length !== 0) {
 // final post data or mutation

  await nextMutation.mutateAsync(saveData);

}},Promise.resolve())};

您可以访问代码沙箱

简短摘要:我想发布每个项目数组,但只有以前的请求得到解决,无论它们是对还是错。然后我将所有已解析的响应收集到另一个数组中。最后,我在另一个 post 方法中发送了该数组。

© www.soinside.com 2019 - 2024. All rights reserved.