I have a value in firebase I need to increment, it's subject to race conditions so I'd prefer to do this all in one.
node: {
clicks: 3
}
I need to set clicks = clicks + 1
so long as clicks < 20
. Is there a single call I can make from the Web API to do this?
There's a new method ServerValue.increment()
in firebase JavaScript SDK v7.14.0
It's better for performance and cheaper since no round trip is required.
See here
Added ServerValue.increment() to support atomic field value increments without transactions.
API Docs here
Usage example:
firebase.database()
.ref('node')
.child('clicks')
.set(firebase.database.ServerValue.increment(1))
Or you can decrement, just put -1
as function arg like so:
firebase.database()
.ref('node')
.child('clicks')
.set(firebase.database.ServerValue.increment(-1))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With