ToklCz
ToklCz

Reputation: 288

Firestore initial update is not recognized. Why?

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.

Upvotes: 2

Views: 58

Answers (3)

Tristan
Tristan

Reputation: 1790

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

Upvotes: 1

tony19
tony19

Reputation: 138556

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.

Upvotes: 1

ToklCz
ToklCz

Reputation: 288

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

Upvotes: 0

Related Questions