5

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.

5
  • Does it make a difference if you use the same ref to perform the updates on? Ex: firebase.google.com/docs/firestore/manage-data/… Commented Jan 27, 2019 at 14:51
  • No, I could do as in the docs you suggested. It looks a bit better (I updated my questions's code). However in order to be sure the arrayRemove was successful and the promise has not been rejected for any reason, I still need to use the promise "happy path" before adding the new value of the object. However now the code looks better, therefore probably this is the only way to go. Commented Jan 27, 2019 at 15:13
  • Hm, I see. I was wondering if the ref refetch was making that happen, but I guess it'll react to both updates. Are you able to pipe the firebase list result and have a "takeWhile" style operator that won't update when you are updating the store? Ex: set a subject to true/false and use that on the firestore fetch for the list Commented Jan 27, 2019 at 15:17
  • I can try to implement such a logic to prevent the flickering effect. Commented Jan 27, 2019 at 15:22
  • This is creating duplicates for me, not updating the original item in the array Commented May 17, 2019 at 3:14

1 Answer 1

1

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

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

Comments

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.