Home > Blockchain >  How do I save multiple instances of the same JS code on firebase?
How do I save multiple instances of the same JS code on firebase?

Time:08-13

Sorry I don't code much and have adapted this code, so help would be greatly appreciated. I'm trying to emulate a shopping page where you can 'like' a product and shows number of 'likes' for each product.

What is happening: When I click on different instances of the 'like' button they get saved as one instance on firebase and all the 'like' counters show the same number of 'likes'

What I want: Every time I click a different instance of the 'like' button I want it saved as a different instance on firebase so the counts are different for each 'like' button.

var dCounters = document.querySelectorAll('.CountLike');
[].forEach.call(dCounters, function(dCounter) {
  var el = dCounter.querySelector('button');
  var cId = dCounter.id;
  var dDatabase = firebase.database().ref('Like Number Counter').child(cId);

  // get firebase data
  dDatabase.on('value', function(snap) {
    var data = snap.val() || 0;
    dCounter.querySelector('span').innerHTML = data;
  });

  // set firebase data
  el.addEventListener('click', function() {
    dDatabase.transaction(function(dCount) {
      return (dCount || 0)   1;
    });
  });
});
.CountLike div {
  display: inline-flex;
}

.item-like {
  font-size: 18px;
  display: inline-block;
  margin-top: 10px;
}

.counterStat {
  margin-right: 15px;
  margin-top: 5px;
}

.heart {
  width: 32px;
  height: 32px;
}

.btn {
  background: none;
  border: none;
  cursor: pointer;
}
<div>
  <div >
    <div  id="Like Count">
      <div >
        <span >0</span>
        <button ><img src="https://www.svgrepo.com/show/164008/heart.svg"  alt="the heart-like button"></button>
      </div>
    </div>
  </div>
</div>
<div>
  <div >
    <div  id="Like Count">
      <div >
        <span >0</span>
        <button ><img src="https://www.svgrepo.com/show/164008/heart.svg"  alt="the heart-like button"></button>
      </div>
    </div>
  </div>
</div>

CodePudding user response:

Below snippet should do it for now. Both of your elements have the same id value set which is set as id="Like Count" So right now you just end up writing and reading from the same field for every cell you have.

As it is also stated on this link you should always make sure the id values you assign are unique.

   <div>
    <div >
      <div  id="xyz">
        <div >
          <span >0</span>
          <button ><img src="https://www.svgrepo.com/show/164008/heart.svg"  alt="the heart-like button"></button>
        </div>
      </div>
    </div>
  </div>
  <div>
    <div >
      <div  id="xyzt">
        <div >
          <span >0</span>
          <button ><img src="https://www.svgrepo.com/show/164008/heart.svg"  alt="the heart-like button"></button>
        </div>
      </div>
    </div>
  </div>
  • Related