1

On my database i have a variable called user points, and i want to increase that variable by a value, lets say by 10, everytime i want.

I am doing this:

on firebase:

update({userPoints: +pointsToGet})

i am using the + to increase the value, but its not working. Is there any way that i can increase the userPoints without using the variable user points like this : userPoints = userPoints + pointsToGet

i tried using ++pointsToGet but it didnt work either

0

1 Answer 1

2

For Firestore

Yes you can by using firebase.firestore.FieldValue.increment(...).

update({ userPoints: firebase.firestore.FieldValue.increment(pointsToGet) })

For more information check out this tutorial: https://fireship.io/snippets/firestore-increment-tips/

Or for the official docs, here: https://firebase.google.com/docs/reference/js/firebase.firestore.FieldValue#static-increment

For Realtime Database

No there is no solution for that, I would recommend you to stick to the following:

update({ userPoints: oldUserPoints + pointsToGet })

Or check out this answer, where someone explains how to do this with a transaction (which is better for race conditions): https://stackoverflow.com/a/40405392/9150652

Offtopic

Also just for your information, +pointsToGet returns the numeric value of your variable (which probably already is a number, so it will just return that number).

It is not used to add 1 to a variable. You can transform a string to a number with it. I hope the following snippet explains it a little:

const createLog = (result) => { // Just a helper, so that we can see the "" for strings in the console
  return JSON.stringify({result});
}

console.log(createLog( '123' ));
console.log(createLog( +'123' ));
console.log(createLog( '123' + '123' ));
console.log(createLog( +'123' + +'123' ));

Sign up to request clarification or add additional context in comments.

1 Comment

Answer is nice, but it is related to Firestore. But seems author is asking about the Firebase (real-time db)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.