Aleks Be
Aleks Be

Reputation: 63

How to get json with Vue and Fetch Api

I have a simple code based on Vue.js:

const app = new Vue({
    el: 'vue-app',
    data: {
        displayedBooks: {}
    },
    created() {
        fetch('/library').then(response => response.json())
            .then((data) => this.data.displayedBooks = data);
    }
});

But I got an exception:

Uncaught (in promise) TypeError: Cannot set property 'displayedBooks' of undefined at fetch.then.then (main.js:8)

Why this simple code is not works well?

Upvotes: 1

Views: 11508

Answers (2)

Masterdash
Masterdash

Reputation: 36

const app = new Vue({
    el: 'vue-app',
    data: {
        displayedBooks: {}
    },
    created() {
        fetch('/library').then(response => {
            this.displayedBooks = response.data
    }, error =>{
       console.log(error)
   })
});

Upvotes: 1

Aleks Be
Aleks Be

Reputation: 63

It'd just be this.displayedBooks, not this.data.displayedBooks. Everything in your Vue data parameter gets attached to this directly.

Upvotes: 2

Related Questions