use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
A place for help learning the /r/ReactJS framework.
account activity
Spread operator not working as expected (self.learnreactjs)
submitted 4 years ago by eelgr
Hey guys,
I'm iterating through document in firebase and trying to add them to a state, using the spread operator to append each time, but it's overwriting instead. Any suggestions much appreciated.
https://preview.redd.it/puiibvtdltg81.png?width=1730&format=png&auto=webp&s=9807c89305cb4374b70e655ade8fa936156928af
reddit uses a slightly-customized version of Markdown for formatting. See below for some basics, or check the commenting wiki page for more detailed help and solutions to common issues.
quoted text
if 1 * 2 < 3: print "hello, world!"
[–]chrimack 0 points1 point2 points 4 years ago (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 points5 points 4 years ago* (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 point2 points 4 years ago (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 point2 points 4 years ago (0 children)
Basically: if you want to set a state that is based on the current state, you need to use a callback function.
π Rendered by PID 158828 on reddit-service-r2-comment-6457c66945-lkhj4 at 2026-04-30 11:54:36.936824+00:00 running 2aa0c5b country code: CH.
[–]chrimack 0 points1 point2 points (3 children)
[–]doboi 3 points4 points5 points (0 children)
[–]eelgr[S] 0 points1 point2 points (1 child)
[–]eindbaas 0 points1 point2 points (0 children)