Reputation: 498
I have this simple code which I try to update my firebase realtime db.
When I use update()
the code goes into an infinite loop in the line: return update(listsRef, updates)
:
const HandleEditFormSubmit = (event) => {
event.preventDefault()
//Updated contact information
const updatedContact = {
id: editContactId,
fullName: editFormData.fullName
}
//Updating Firebase RT-DB
onValue(listsRef, (snapshot) => {
const jsonObject = snapshot.val()
for (const [key, value] of Object.entries(jsonObject)) {
if (value['id'] === editContactId) {
const updates = {}
updates[key] = updatedContact
return update(listsRef, updates)
//TODO: WHY DO I HAVE AN INFINITE LOOP HERE?!
}
}
})
}
And the error looks like this:
Until everything crashes:
But when I change the code to this one using get()
everything works well:
const HandleEditFormSubmit = (event) => {
event.preventDefault()
//Updated contact information
const updatedContact = {
id: editContactId,
fullName: editFormData.fullName
}
//Updating Firebase RT-DB
get(listsRef).then(snapshot => {
if(snapshot.exists()){
const jsonObject = snapshot.val()
for (const [key, value] of Object.entries(jsonObject)) {
if (value['id'] === editContactId) {
const updates = {}
updates[key] = updatedContact
return update(listsRef, updates)
}
}
}
})
}
I already read the Firebase Docs (Modular SDK v9) but I didn't find why update()
goes into an infinite loop and update()
after get()
works just fine & I don't have a clue why my code works now.
I'm just a beginner with Firebase & React, I'll appreciate any help to understand better why.
Upvotes: 0
Views: 149
Reputation: 2165
onValue trigger when changes happen on specific location listsRef reference.
the issue here that you are updating the same location listsRef that made onValue() run again
Upvotes: 1