How To Avoid Racing Issues Using Cloud Firestore Triggers
I'm using Cloud Firestore onCreate triggers on Firebase, where client is a React Native app.
Users are getting points by writing in a separate collection which has onCreate
triggers attached. User can create multiple single-point documents one after the other.
Example: User 1 gets 3x100 points. This creates three documents and trigger is triggered three times.
First executiong finds last user point amount (for example 500) increases it by 100, and saves new state = 600 into user profile. Meanwhile, before this has finished, second trigger is triggered, reads previous state which is still 500 since the previous trigger isn't finished, increases it by 100, and saves 600 also. Third one manages to do the same.
In the end user should have gotten 500 + 100 + 100 + 100 = 800 points, but he has 600 only because last trigger has been triggered before the first one has finished updating user profile and all inbetween changes are overwriten.
How to tackle this?
Thanks.
Answer
You need to use a transaction to make sure that all access to a common document is performed atomically. This will ensure that competing writes don't clobber each other's updates. In the event that there is a race to update, the transaction handler will be retried with updated data.
Related Questions
- → How can I query Firebase for an equalTo boolean parameter?
- → How can I access nested data in Firebase with React?
- → Firebase simple blog (confused with security rules)
- → Removing item in Firebase with React, re-render returns item undefined
- → AngularJS Unknown Provider Error (Firebase & AngularFire)
- → How do you pass top level component state down to Routes using react-router?
- → "this" is null in firebase query function in reactjs
- → Angular Module Failed to Load
- → Multiple dex files define Lcom/google/android/gms/internal/zzrx;
- → Joining Firebase tables in React
- → How can I make add firepad to my reactjs project?
- → How to use Cloud Functions for Firebase to prerender pages for SEO?
- → React.js component has null state?