0

I can't access the data of fbData. When I log the data inside the function it is accessible, but is not outside of the function. Any ideas what I am doing wrong here?

<template>
    <div id="main">
        <div id="cardFront">{{fbData}}</div>        
    </div>  
</template>
<script>
    module.exports = {
        data () {
            return {
                fbData:[],
        }
    },
    created() {
        var ref = firebase.database().ref("Users/MK01111000/cards")
        ref.once("value")
        .then(function(snapshot) {
            this.fbData = snapshot.val()
            console.log(this.fbData) //{-Ltl2osulqmFnKIRoT5Q: {…}, -LtnKKxEWkEH7DbV7VB-: {…}}
        }) 
        console.log(this.fbData) // []         
    }
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
MK01111000
  • 770
  • 2
  • 9
  • 16
  • This is the expected behavior. Data is loaded from Firebase asynchronously, which means that by the time your `console.log` outside of the callback runs, the data hasn't loaded yet. All code that needs the data needs to be inside the callback, or be called from there. See https://stackoverflow.com/q/23667086 (for the generic explanation), and https://stackoverflow.com/a/40688890 (for an explanation related to Firebase). – Frank van Puffelen Nov 17 '19 at 15:21
  • Thank you for explaining that. I can't however get it to work in my example. This is what I tried: `created() { async getfbData() { const eventref = this.db.ref('Users/MK01111000/cards'); const snapshot = await eventref.once('value'); const value = snapshot.val(); console.log(value) } },` – MK01111000 Nov 18 '19 at 10:58
  • That seems like a new problem, so you might want to open a new question for it. To have the best chance of getting an answer, be sure to include what the code does *and* what you expected it to do. – Frank van Puffelen Nov 18 '19 at 16:01
  • Thanks Frank, will do so – MK01111000 Nov 18 '19 at 19:48

0 Answers0