Firestore initial update is not recognized. Why?

Viewed 54

I have this code, which is updating the number of likes on the movie. But the first update is not recognized. So if I click the button 5 times. On firestore is updated only 4.

async liked() {
            await db.collection('movies').doc(this.movie.id).update({
                likes: this.movie.likes++
            });
        },

I any more code needed I will update the question.

3 Answers

Postfix increment (x++) changes the variable after evaluation, so your original code updates likes to the current value of this.movie.likes and then increments it.

That is, this code:

await db.collection('movies').doc(this.movie.id).update({
  likes: this.movie.likes++
});

...is equivalent to:

await db.collection('movies').doc(this.movie.id).update({
  likes: this.movie.likes
});
this.movie.likes += 1;

Conversely, prefix increment (++x) changes the variable before evaluation:

await db.collection('movies').doc(this.movie.id).update({
  likes: ++this.movie.likes
});

...which is equivalent to:

this.movie.likes += 1;
await db.collection('movies').doc(this.movie.id).update({
  likes: this.movie.likes
});

But it's probably clearer to increment the variable on its own line, as you've discovered in your answer.

As the other answers have pointed out, you need to increment the value before updating your document. However, I will give you another option which is to let Firestore increment the value for you. And doing it this way will protect against race conditions where multiple updates could come in at once.

Use the Firestore.FieldValue.increment operation in your update query. https://firebase.google.com/docs/reference/js/firebase.firestore.FieldValue#static-increment

Something like

async liked() {
            await db.collection('movies').doc(this.movie.id).update({
                likes: firebase.Firestore.FieldValue.increment(1)
            });
        }

It just needed to do the calculation before the update

async liked() {
            this.movie.likes++
            await db.collection('movies').doc(this.movie.id).update({
                likes: this.movie.likes
            });
        },
Related