简体   繁体   中英

Getting 'max call stack size exceeded' when incrementing a node in Firebase

I'm trying to increment my 'week' value in firebase by 1.

One solution i've been trying was this:

var ref = db.ref();
    ref.on('value', function (data) {
        var week = data.val().week + 1;
        ref.update({
            week
        });
    });

but it throws a "max call stack size exceeded" error (Even though firebase still updates appropriately)

I also tried

var ref = db.ref('week');
    ref.on('value', function (data) {
        var week = data.val();
        ref.set(week+1);
    });

this works as well, but it throws the same error

Can someone provide a solution that doesn't throw an error? thanks

The reason is because you're using on() to read the data. When you use on(), you're setting up a listener that gets invoked any time the data at the location changes. So what you have written does this:

  1. Listen to the location 'week'
  2. When the value is known, or when it has changed , get it from the snapshot
  3. Increment the value by 1, and write it back to 'week'
  4. Since the value of 'week' has changed, goto step 2 so the listener can process the change.

This effectively an infinite loop.

If you just want to increment a single time, use once() instead of on() to read data once .

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