Home > Mobile >  Firebase database. How to append values to array?
Firebase database. How to append values to array?

Time:02-21

I have the following test data

1: {
 
  match: "Game 1",
  scorer: ["foo","bar"] //this could also be an object
}

My question is how do I correctly append new value to an array without overwriting it? My idea was to retrieve existing data then spread it like so [...currentData, "bob"]. Is there a better alternative?

const addScorer = (matchId) => {
 return update(ref(db, path), {
  scorer: ["bob"]
 })
}

CodePudding user response:

There is no atomic operation to add an item to an array directly in the database. This means you'll need to:

  1. Read the array into your application code
  2. Append the item to the array
  3. Write the entire array back to the database

This is one of the many reasons why Firebase recommends against using arrays for lists of data, but instead has a push() operation that circumvents most problems. For more on this, see the link to the document that Nilesh included in their comment, or read this article on Best Practices: Arrays in Firebase.

  • Related