So I am creating a Vuejs application and I am trying to fetch firebase data on ponent mount. That is working, but I try to write the value into a vuejs data property. For this I would only call this.property = snapshot.val();
inside the firebase function (see code below) but that is not working: this is undefined
So my code just is:
export default {
data() {
return {
imageList: "No images!"
}
},
mounted() {
if (!firebase.apps.length) {
// Initialize Firebase
var config = {
...
};
firebase.initializeApp(config);
var database = firebase.database();
var ref = database.ref("images").orderByChild("date");
firebase.database().ref("images/").once('value').then(function(snapshot) {
this.imageList= snapshot.val();
});
}
}
}
I tried calling this.imageList= snapshot.val();
outside of the function with a variable to store the value, and 'this' wasn't undefined anymore, but the data wasn't there because the request hasn't finished yet.
So basically I want to get the snapshot.val(); into this.imageList!
Thanks in advance.
So I am creating a Vuejs application and I am trying to fetch firebase data on ponent mount. That is working, but I try to write the value into a vuejs data property. For this I would only call this.property = snapshot.val();
inside the firebase function (see code below) but that is not working: this is undefined
So my code just is:
export default {
data() {
return {
imageList: "No images!"
}
},
mounted() {
if (!firebase.apps.length) {
// Initialize Firebase
var config = {
...
};
firebase.initializeApp(config);
var database = firebase.database();
var ref = database.ref("images").orderByChild("date");
firebase.database().ref("images/").once('value').then(function(snapshot) {
this.imageList= snapshot.val();
});
}
}
}
I tried calling this.imageList= snapshot.val();
outside of the function with a variable to store the value, and 'this' wasn't undefined anymore, but the data wasn't there because the request hasn't finished yet.
So basically I want to get the snapshot.val(); into this.imageList!
Thanks in advance.
Share Improve this question asked Jul 20, 2017 at 20:00 Janis JansenJanis Jansen 1,0351 gold badge18 silver badges40 bronze badges3 Answers
Reset to default 10You can use es6 arrow function syntax to solve the issue.
firebase.database().ref("images/").once('value').then((snapshot) => {
this.imageList= snapshot.val();
});
or bind this to the context of the function.
var that = this;
Use an arrow function, a closure, or bind
.
firebase.database().ref("images/").once('value').then(snapshot => {
this.imageList= snapshot.val();
});
See How to access the correct this
inside a callback.
You can use bind
as well.
firebase.database().ref('images/').once('value').then(function(snapshot) {
this.imageList = snapshot.val()
}.bind(this))