Chance
Chance

Reputation: 43

For Loop only taking last iteration when using FireStore

I'm trying to compare values in a Firebase/Firestore database, and I am changing a div border style based on if a value is true or not. The For loop goes through each time, but only keeps the last one. So it's rewriting over in the loop I guess, but I don't understand how?

// HANDLES THE FRONTEND TOGGLE/COLOR CHANGE OF SKILLS ON THE FRONTEND
for (var i = 0; i < skills.length; i++) {
    var toggledSkills = skills[i].id;
    console.log(toggledSkills);
    var query = db.collection('users').where(toggledSkills, "==", true);

    query.get().then(function(querySnapshot) {
        if (querySnapshot.empty) {
            // IF THE SKILL IS NOT LEARNED, PLAIN STYLING
            document.getElementById(toggledSkills).parentNode.style.border = "2px solid purple";
        } else {
            // IF THE SKILL IS TRUE/ALREADY LEARNED, COOL STYLING
            document.getElementById(toggledSkills).parentNode.style.border = "2px solid green";
        }
    });

}

Upvotes: 0

Views: 925

Answers (1)

Artur Carvalho
Artur Carvalho

Reputation: 7167

If you are getting more than one element, you should go through all the list with forEach.

Something like this:

db.collection("cities").where("capital", "==", true)
    .get()
    .then(function(querySnapshot) {
        querySnapshot.forEach(function(doc) {
            // doc.data() is never undefined for query doc snapshots
            console.log(doc.id, " => ", doc.data());
        });
    })
    .catch(function(error) {
        console.log("Error getting documents: ", error);
    });

You can find more info here: https://firebase.google.com/docs/firestore/query-data/get-data

Upvotes: 1

Related Questions