4

I note that there's instructions on how to increment values for realtime database in Javascript v8:

===

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))

However, I notice that there isn't any reference to ServerValue in the v9 documentation.

Does this mean that this functionality is not available?

I've tried converting it to v9 on my own but I've been unsuccessful so far:

const setWeekComplete = () => {
    set(ref(database, `users/${user}/streakCounter`), {
        weeks: database.ServerValue.increment(1)
    });
  }    
Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121
Lloyd Rajoo
  • 137
  • 2
  • 13

1 Answers1

8

It is still available in V9 and you'll find it here in the doc. So the following should do the trick.

import { ... , increment } from 'firebase/database';

// ...

const setWeekComplete = async () => {
    await set(ref(database, `users/${user}/streakCounter`), {
        weeks: increment(1)
    });
  } 
Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121
  • just to check - would you recommend using async await for all realtime database actions? I noticed that the documentation doesn't use async and await – Lloyd Rajoo Nov 20 '21 at 11:30
  • 3
    `set()` is an asynchronous method. Therefore you usually use async/await to know when it has been executed (and get the result if it returns a result, which is not the case with `set()`), but if you don’t care about the result you can call it without await. – Renaud Tarnec Nov 20 '21 at 12:24
  • understood, thank you! – Lloyd Rajoo Nov 27 '21 at 02:32