How to pass a JS loop variable into a FireStore get

I’m trying to pass a variable during a for loop into a firebase database, however it comes back as the same value in each loop, I’ve commented in the code, where the issues happen.

    var countElements = document.querySelectorAll("[data-voteCount]");

    function displayVotes() { 

    for (i = 0; i < countElements.length; i++) {
                    
        var elementID = countElements[i].dataset.votecount;
        
        docRef = firestore.doc("Votes/product-" + elementID);
        
        console.log(elementID); // when it's logged here the ID's are correct. 
        
         docRef.get().then(function(doc) { // how do i pass it into here?? 

            if (doc.exists) {
                
                console.log('document exists ' + elementID); // when logged here the ID is always 1 

            }
             
             else {
                 
                console.log('document not found ' + elementID); // when logged here the ID is always 1 

            }

            });

        }

    }
<div data-voteCount="1"></div>
<div data-voteCount="2"></div>
<div data-voteCount="3"></div>

75 thoughts on “How to pass a JS loop variable into a FireStore get”

Leave a Comment