Home > Software design >  Updating Array of Objects in Firebase Realtime Database in React js
Updating Array of Objects in Firebase Realtime Database in React js

Time:12-27

I have a problem with updating certain properties of an array of objects in a real-time database in Firebase.

My object looks like the following (see picture).

Now I want to update the IsComing property of the second participant object.

enter image description here

At the moment I use the updateIsComming() function, but this is not very convincing, because I have to rewrite the whole object.

 function updateIsComming() {
   
    const db = getDatabase();
    update(ref(db, " your_path/EventModel/"   modelkey ), {
      Location: "London",
      Participants: [
        { Name: "Bella2", IsComming: "true" },
        { Name: "Tom", IsComing: "true" },
      ],
    });

Instead, I just want to reference the specific prop from that array. For example

Participant[1].IsComming = false;

Is there any way I can access a specific array of an object directly.

CodePudding user response:

Arrays as a data structure are not recommended in Firebase Realtime Database. To learn why, I recommend reading Best Practices: Arrays in Firebase.

One of the reasons for this is that you need to read the array to determine the index of the item to update. The pattern is:

  1. Read the array from the database.
  2. Update the necessary item(s) in the array in your application code.
  3. Write the updated array back to the database.

As you already discovered, this is not ideal. As is common on NoSQL databases, consider an alternative data structure that better suits the use-case.

In this case, an alternative data structure to consider is:

Participants: {
  "Bella2": true,
  "Tom": true
}

In there, we use the name of the participant as the key which means:

  • Each participant can be present in the object only once, because keys in an object are by definition unique.
  • You can now update a user's status by their name with: update(db, "your_path/EventModel/" modelkey "/Participants/Tom", false).
  • Related