简体   繁体   中英

How to increment values in Firebase Realtime Database (v9)

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM