angularfire2 best way to increment a value?
Firestore now has increment()
which correctly increments a field even if multiple users are competing to edit at the same time
Incrementing Values Atomically with Cloud Firestore
To use this in angularfire2
import { firestore } from 'firebase/app';
incrementLike(userToIncrementLike) {
const increment = firestore.FieldValue.increment(1);
const userLike = this.af.doc(`users/${userToIncrementLike.uid}`);
userLike.update({ likes: increment });
}
I used firestore directly since I couldn't find FieldValue
in angularfire2.
It isn't necessary to define an object or to use the update()
method. The object already exists in the database, so you can just work on it there. This is actually the purpose of transaction()
--to work on the data at the data location and therefore prevent conflicts; e.g., two users updating the same value at the same time.
You can also use the template literal in your path if you like. :) (Note the backticks instead of single quotes.)
incrementLike(userToIncrementLike){
this.af.database.object(`users/${userToIncrementLike.uid}/likes`).query
.ref.transaction(likes => {
if (likes === null) {
return likes = 1;
} else {
return likes + 1;
}
})
}
Update: September, 2019. Use query
instead of $ref
.
"angularfire2 V5" Solution:
incrementLike(userToIncrementLike){
this.af.database.object(`users/${userToIncrementLike.uid}/likes`)
.query.ref.transaction((likes => {
if (likes === null) {
return likes = 1;
} else {
return likes + 1;
}
})};