setState() not working in class based component in react js

Viewed 29
  constructor(){
    super();
    this.state = {
      articles: this.articles,
      loading: false
    }
  }

  //always run after the render method
  async componentDidMount(){
    let url = "https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=7d5e22019e7e4b519b0a7776738ac065";
    let data = await fetch(url);
    let parseData = await data.json();
    let updateArticle = parseData.articles;
    this.setState({
        articles: updateArticle
    });    // console.log(this.articles)
  }

I was expected to replace the articles with updateArticle using setState() But it is not working but i got the correct value in the updateArticle but cant asssign to articles

1 Answers

super() should include props of the component. this scope would not work otherwise. check this related article.

// incorrect way
constructor() {
  super();
  // ...
}

// correct way
constructor(props) {
  super(props);
  // ...
}
Related