0

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"]
 })
}
1

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This is no longer true. There is a FieldValue.arrayUnion and arrayRemove.
The question is about the Realtime Database, while FieldValue.arrayUnion and arrayRemove are only available for Cloud Firestore.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.