简体   繁体   中英

Updating Array of Objects in Firebase Realtime Database in React js

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.

在此处输入图像描述

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.

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) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM