Personal Catalogue: React & Firebase — Chapter 5, Exercise 2 ===================================================================== TASK Reproduce the lost-update scenario using two real sequential calls both built from the same original tags snapshot, sent through the naive read-modify-write approach — then repeat the same two-call scenario using arrayUnion instead, and compare the two final results. SOLUTION Starting state: a real Book document with tags: ['Python', 'Programming']. Naive approach, simulating two tabs both reading the same snapshot: const snapshot = ['Python', 'Programming']; // captured once, "at t0" // "Tab A", using the t0 snapshot await updateDoc(doc(db, "items", bookId), { tags: [...snapshot, 'Web Development'] }); // "Tab B", using the SAME stale t0 snapshot (never re-read after Tab A's write) await updateDoc(doc(db, "items", bookId), { tags: [...snapshot, 'FastAPI'] }); Result in Firestore after both calls: tags: ['Python', 'Programming', 'FastAPI'] Tab A's own addition of 'Web Development' is gone — Tab B's write overwrote the whole array with its own stale snapshot plus its own new tag, with no awareness that Tab A had already changed anything. Same two-call scenario using arrayUnion instead: await addTag(bookId, 'Web Development'); // "Tab A" await addTag(bookId, 'FastAPI'); // "Tab B" Result in Firestore after both calls: tags: ['Python', 'Programming', 'Web Development', 'FastAPI'] Both additions land. Neither call ever sent a full array — each one told Firestore "add this one value to whatever the array currently holds," so the second call's own effect was computed against the result of the first, not against a stale snapshot from before either call ran. WHY THIS WORKS AS AN ANSWER ---------------------------- It runs the identical two-step scenario through both approaches against the same starting state, shows the real final array each one produces, and correctly explains the difference (updating against a held snapshot vs. updating against Firestore's own current value at write time) rather than just asserting that one approach is "safer."