In the code below I put a post REQ function inside a forEach loop and send a req for every selectedService entry that exists within that array. Then when the loop finished I fetch all the userServices and set that to my state.
const handleAddServiceToUser = async () => {
if (selectedServices === []) {
setErr('Please Select A Service')
} else {
selectedServices.forEach(async (selectedService) => {
await addNewUserService(userId, selectedService.id)
})
const res = await getUserServicesList(userId)
setUserServices(res.data)
handleClose()
if (err !== '') {
setErr('')
}
setSelectedServices([])
}
}
I have never seen or tried anything like this before (async forEach). The code does seem to be working when I test it in my client. I am assuming it is probably not a best practice to do something like this? Is this acceptable in terms of performance? And if not what is an alternative?