0

I am currently upgrading an old IONIC 1 app (adding new features). I have read a lot of threads but didn't find any answer to my question.

First of all, my Firebase Database structure looks as follows:
-products
--productId
--- imageurl
--- price
--- title
--- likes: 0

I would like to increment the value of child likes everytime a user triggers (for instance clicks a like button).

my service.js function looks as follows:

incrementLikeproduct: function(prodId){

        return ref.child('products').child(prodId).child('likes').set( xxxx );  
    },

I have tried to retrieve the current value of the likes child object from firebase as a var and add +1; but didn't get anything to work properly. I basically do not know how to replace the xxxxx in my function to obtain the expected result.

My question is: How shoud I write the incrementLikeproduct function to increment the likes child value in firebase? I have read about asynchronous listener but can't figure out how to implement it inside my service.js.

I know that IONIC1 is outdated but I had already a solid piece of code to which I wanted to add new features without starting the whole app dev from scratch.

I am quite noob with JS and would be greateful if someone could give me a hint :-).

alex83803
  • 102
  • 7

1 Answers1

1

Something like this maybe

incrementLikeproduct = function(prodId) {
  // fetch value first
  ref
    .child("products/" + prodId + "/likes")
    .once("value")
    .then(snapshot => {
      var oldLikes = snapshot.val();
      ref.child("products/" + prodId + "/likes").set(oldLikes + 1);
    });
};
Tanmay_vijay
  • 569
  • 3
  • 12