0

I want to send multiple post requests with one click. Every post request will be sent after the previous one is resolved (whether it's right or wrong). Then I need to collect all resolved responses in an array and finally send that array. Note: I'm using React Query. If it's a bit confusing, I've added the code and also the code sandbox . https://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>
)

1 Answers1

0

I've solved the problem. Thanks to Dave Gray. His explanation was very clear. I followed his solution and it worked pretty well.

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())};

You can visit the code sandbox

Short Summary: I want to post each array of items, but only previous requests are resolved, whether they're right or wrong. Then I collected all the resolved responses in another array. Finally, I sent that array in another post method.