Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment firebase value from javascript, subject to constraint

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?

like image 883
Bonnie Scott Avatar asked Feb 16 '17 14:02

Bonnie Scott


1 Answers

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))
like image 107
Oleg Dater Avatar answered Oct 24 '22 22:10

Oleg Dater