Reputation: 986
I have a Button which does a POST request when it's clicked. While waiting for the response I have a Loading animation. However now I want this button not to only make 1 post request I want it to do 100 post requests with 1 click
My Button
<Form>
<Form.Group>
<Button variant='success' className='button' onClick={handleClick} id='create'>Create Sales Order</Button>
</Form.Group>
</Form>
My Loader while waiting for the API Call
<BeatLoader
css={override}
size={30}
// size={"150px"} this also works
color='#b51a82'
loading={isLoading}
/>
this is the handleClick function which gets called when the button is pressed
async function handleClick (event) {
switch (event.target.id) {
case 'create':
setLoading(true)
break
case 'delete':
// code for delete case
break
default:
console.log('click didnt work')
}
}
my useEffect Hook. In this hook I tried to put the content of the createSalesOrder function in a loop, which does not work because it will break my loading animation (the loading animation will not stop)
useEffect(() => {
async function createSalesOrder () {
const res = await axios.post('http://localhost:5000/')
console.log(res)
setValue([...value, res.data])
return (res)
}
if (isLoading) {
createSalesOrder().then(() => {
setLoading(false)
})
}
}, [isLoading])
Upvotes: 1
Views: 231
Reputation: 25855
You can use Promise.all
to wait for one or more promises to complete. It returns a single promise that "wraps" all of the other promises which will resolve when all of the promises have resolved, or reject immediately if any one of the promises is rejected.
If you want to want to wait for all of the promises to finish, even if some are rejected, then use Promise.allSettled
useEffect(() => {
async function createSalesOrder () {
const res = await axios.post('http://localhost:5000/')
console.log(res)
setValue([...value, res.data])
return (res)
}
if (isLoading) {
const finished = _ => setLoading(false);
// Wait for all of the sales orders to finish
Promise.all(
// Create an array of 100 promises:
// Quickly create an array with 100 entries
[...Array(100).keys()].map(
// For each entry, submit a request to create a sales order
// and return a promise
createSalesOrder
)
).then(
// When all of the promises have resolved, end your animation:
finished,
// Make sure you stop the animation even if an error occurred:
finished
);
}
}, [isLoading])
Also, keep in mind that the promises will be resolved/rejected in whatever order they come back from the server, not necessarily in the order they were sent out. This means that it is totally possible that the first order you created will be resolved somewhere in the middle, that the last order you created will be resolved first, etc., and that if you repeat the logic, the order in which they are resolved will be different each and every time.
Upvotes: 2