0

I am trying to fetch news articles from an external source, it returns JSON object. I want to assign its articles property to a variable in my component. Somehow this error is occurring.

Uncaught (in promise) TypeError: Cannot set property 'articles' of undefined

Any suggestions on how to overcome this problem?

export default {
  name: "blog",
  data() {
    return {
      articles: [],
    };
  },
  mounted() {
    // API call
    this.fetchnews();
  },
  methods: {
    fetchnews(){
      fetch(
      "----------------------news link-------------------------"
    )
      .then(function(response) {
        return response.json();
      })
      .then(function(json_data) {
        //console.log(typeof(json_data))
        this.articles = json_data.articles
      });
    }
  }
};
0

4 Answers 4

2

As the first contributor properly noticed - the issue is this.articles inside your latest function doesn't really point to what you need. If you are limited to ES5 then stick to the first answer. However if you can use ES6 then simply get advantages of short syntax:

export default {
  name: "blog",
  data() {
    return {
      articles: [],
    };
  },
  mounted() {
    // API call
    this.fetchnews();
  },
  methods: {
    fetchnews(){
      fetch("----------------------news link-------------------------")
      .then(response => response.json())
      .then(json_data => this.articles = json_data.articles);
    }
  }
};
  • in this case this will properly point to the outer scope.

Also why do you need two then()? You could collapse them into one:

.then(response => this.articles = response.json().articles);
Sign up to request clarification or add additional context in comments.

2 Comments

is this even composition API? looks more like options API to me...
@RobertoDVLeonardo composition API didn't exist in Feb 2020 :))
1

using function keyword creates new scope. if you use arrow syntax like () => {} you can use parent scope and set articles via this.articles

fetchnews(){
  fetch()
  .then((response) => {
    return response.json();
  })
  .then((json_data) => {
    this.articles = json_data.articles
  });
}

Comments

0

inthis.articles: here this refers to the function not vue instance , so you may define this outside the function like:

let This=this

and inside your function :

This.articles = json_data.articles This here refers to vue instance

Comments

0

javascript function as global scope make sure use to assign function to variables

Comments

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.