In my React app, I have an stateful array and setter [data, setData]
which I would like to iterate through, and for each element, call a series of async functions.
I need each operation to occur sequentially, so my code looks like:
async save = () => {
data.forEach(async(item) => {
// Each of these are network requests, and they need to happen sequentially.
await post();
await update();
await publish();
});
};
My question is: What happens if, during this process, another process calls setData()
? Is it possible that data
will be mutated in the middle of save()
being executed? If so, how will the forEach
respond? Will it continue to iterate over the original state before the mutation, or will the mutation take effect within the context of the loop?
(I understand that I should avoid creating this type of situation in the first place, but if React has some sort of built in protection against this, then I'd like to avoid adding unnecessary abstraction to avoid something that won't actually happen)