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.