Search code examples
firebasepolymerpolymer-1.0polymerfire

Polymer 1.x: How to fetch data using firebase-document imperatively inside a custom behavior


I am trying to fetch data using a dynamic, imperatively created firebase-document element inside a custom behavior.

I have the following code. Notice the first console.log correctly logs as expected. But the second never logs anything. Where am I going wrong?

my-behavior.html
<link rel="import" href="../../bower_components/polymer/polymer.html">
<link rel="import" href="../../bower_components/polymerfire/polymerfire.html">
...
getUserLocalSeries: function(uid) {
  var doc = document.createElement('firebase-document');
  var path = ['users', uid, 'local'].join('/');
  doc.appName = 'app';
  doc.path = path;
  var _this = this;
  console.log('path', path); // Logs fine
  doc.addEventListener('response', function(e) {
    console.log('doc', doc.lastResponse); // Doesn't log
    _this.set('userLocalSeries', doc.lastResponse);
  });
  this.set('userLocalSeries', doc.data);
},

Solution

  • I'd strongly recommend just using the Firebase JS SDK for this instead:

    getUserLocalSeries: function(uid) {
      var path = ['users', uid, 'local'].join('/');
      var _this = this;
      firebase.database().ref(path).on('value', function(snap) {
        _this.set('userLocalSeries', snap.val());
      });
    }
    

    You can use the SDK so long as you have a firebase-app in your project. This example requires that you omit the name attribute from firebase-app, but you could also do e.g. firebase.app('app').database().ref() instead.