1

Fetching data from json data in vue function. Then trying to return that in my vue template. It is not returning anything on the template. But in console the variable is showing desired data. For some reason the variable is not working only on the template. I have used this same method to fetch and show data in other places, it worked perfectly. But here is not. It is not even showing any javascript error.

Here is my template:

    <div>
          <ul>
            <li v-for="feed in feeds" v-bind:key="feed.id">
                <h3>{{feed.title}}</h3>
                <p>{{feed.body}}</p>
            </li>
          </ul>
    </div>    

Here is the script:

export default {
data(){
    return {
        feeds: []
    }
},
created(){
    this.fetchFeeds();
},
methods:{
    fetchFeeds(page_url){
        let vm = this;
        page_url= page_url ||'feeds/api'
        fetch(page_url)
        .then(res => res.json())
        .then(res =>{
            this.feeds = res.data;
            console.log(this.feeds); //this showing data in console

        })
        .catch(err => console.log(err));
    }
  }
}

1 Answer 1

0

It is the matter of the scope changing this object. When you call fetch() this does not refer to VueJs this object anymore. Just use the vm variable to which you assigned this object.

export default {
data(){
    return {
        feeds: []
    }
},
created(){
    this.fetchFeeds();
},
methods:{
    fetchFeeds(page_url){
        let vm = this;
        page_url= page_url ||'feeds/api'
        fetch(page_url)
       // .then(res => res.json())
        .then(function(res){
            vm.feeds = res.data;
            console.log(vm.feeds); //this showing data in console

        })
        .catch(err => console.log(err));
    }
  }
}
Sign up to request clarification or add additional context in comments.

4 Comments

Tried that already. still same problem. Showing data in console, but not in template
@Rafaeatul, did you try to remove/comment first then from promise?
also, use full function instead of arrow
yes I did. I have noticed something very interesting actually, when I go to other page and do a cache clearing refresh, and come back to this page using back arrow, the data is showing! then when I am refreshing the page, the data is gone again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.