Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase update an object inside a nested array

In Firestore I have a Document with a property(named "items") of type array. The array contains ShoppingItem objects with the following structure:

export class ShoppingItem {
 id?: string; 
 name: string;
 checked = false;
}

And for the sake of completion, below the document structure:

export interface ShoppingList {
 id: string;
 name?: string;
 items: ShoppingItem[]; // <-- This is the array property I am updating
}  

From the UI, the user can update the checked property of the object and I want to update the database accordingly. I read from the Firebase documentation that we can use arrayRemove/arrayUnion to atomically remove/add array items.

In order to update an existing item, should I have to remove the old object and add the new one each time (nested promises) like below? Or would it be possible in a more elegant way?

updateItem(listId: string, item: ShoppingItem) {
  const docRef = this.db.collection("list").doc(listId)

  return docref.update({ items: firestore.FieldValue.arrayRemove(item) })
    .then(() => {
    {
      docRef.update({ items: firestore.FieldValue.arrayUnion(item) });
    }
  });
}

Another drawback of removing and adding the item inside the array, is that the updated element flicker in the UI.

like image 688
Francesco Avatar asked Nov 07 '22 21:11

Francesco


1 Answers

Still, there is no way to update the specific field of an array of objects. (arrayRemove/arrayUnion) is the only solution.

like image 95
Saravana Prakash Avatar answered Nov 13 '22 22:11

Saravana Prakash