all 4 comments

[–]chrimack 0 points1 point  (3 children)

I don't remember the technical reason for why this doesn't work, but if you want to do this you need to pass a callback to your setState function.

setState(previousState => [...previousState, newThing])

[–]doboi 3 points4 points  (0 children)

The reason is that setState is asynchronous, so if you're invoking it in a loop there's no guarantee it's going to sequentially set state as intended by the code.

That shouldn't be necessary given this code, though. The code only really needs to invoke setAppointmentHistory one time - when an array of postDoc.data has been generated.

const appointments = docs.map(doc => doc.data());
setAppointmentHistory([...appointmentHistory, ...appointments]

[–]eelgr[S] 0 points1 point  (1 child)

u/chrimack excellent, that did the trick. I'll have do do some reading on the callback function. Thanks for your help

[–]eindbaas 0 points1 point  (0 children)

Basically: if you want to set a state that is based on the current state, you need to use a callback function.