Skip to content

docs: Clarify potential gotcha when overriding serialize in rtdb #1083

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed

Conversation

julienr
Copy link

@julienr julienr commented May 10, 2021

TLDR: The rtdb childRemoved handler uses indexForKey to find the element to delete. This function assumes that a .key property is defined on objects, which won't be the case if you override the serialize option. This can lead to bugs when removing from array.

For example, I had the following, which doesn't define .key:

      await bindFirebaseRef('events', db.ref(FB_EVENT_PREFIX + aoiName + '/'), {
        serialize: (snapshot: firebase.database.DataSnapshot) => {
          const val = snapshot.val()
          val.date = new Date(val.date)
          return val
        }
      })

With this code, whenever I deleted an element from my array, it was always the last one that got removed. Took me a bit of time to figure out why deletion wasn't working, hence this documentation improvement.

The reason is that if .key is not defined, indexForKey will return -1 which ultimately will gets passed to Array.slice which ends up removing the last item.

A better fix might be to throw an error instead of returning -1 in indexForKey. Happy to work on this if that's deemed better.

@posva posva closed this in 402288b Nov 25, 2022
@posva
Copy link
Member

posva commented Nov 25, 2022

Thanks for this, I added a similar comment to the new docs

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants