Search code examples
firebasepolymergoogle-cloud-firestore

put a firestore variable in a polymer template


Maybe I am over thinking it, but I can't figure out a way to put the results of a Firestore query into a Polymer 3 template. For example:

class MyPage extends PolymerElement {

    constructor() {
        super();

        /* somehow set this.users to the firestore users query results */

    }

    static get properties() {

        return {
            users: {
                type: String
            }
        }

    }

    static get template() {
        return html`<div>[[users]]</div>`;
    }
}

Using the following code, which does work correctly and print to the console:

var all_users;

const setsRef = firestore.collection("users");

setsRef.get().then(function(querySnapshot) {

    var users = [];

    querySnapshot.forEach(function(doc) {
        users.push(doc.data().verb);
    });

    all_users = users.join(", ");

    console.log("All users: ", all_users);

    /* run a function here that sets this.users = all_users */

})
.catch(function(error) {
    console.log("Error getting documents: ", error);
});

The problem is, I have to run a function from the Firestore results, while the other is a constructor of an object. I would preferably like to have all of my Firebase queries in an external js file, but this async thought process is confusing me.


Solution

  • Use one of the lifecycle methods to load the users:

    https://www.polymer-project.org/3.0/docs/devguide/custom-elements#element-lifecycle

    class MyPage extends PolymerElement {
        constructor() {
            super();
            this.users = []
        }
    
        static get properties() {
            return {
                users: {
                    type: String
                }
            }
    
        }
    
        static get template() {
            return html`<div>[[users]]</div>`;
        }
    
        async ready() {
          super.ready()
          try {
            const querySnapshot = await firestore.collection("users").get()
            this.users = querySnapshot.map(doc => doc.data().verb).join(", "); 
          } catch (error) {
            console.log(error)
          }
        }
    }
    

    If you don't want to use one of the lifescycle methods, then you can fire your own custom event which your MyPage element can listen for: https://www.polymer-project.org/3.0/docs/devguide/events#custom-events

    I'm not familiar with Polymer, so the above is untested and what I figure from reading the docs.