Computer Crafter
Computer Crafter

Reputation: 323

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

Upvotes: 0

Views: 32

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317692

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.

Upvotes: 1

Related Questions