0

import React, { Component } from 'react'; import NewsItem from './NewsItem';

export class News extends Component {

constructor(){
    super();
    this.state={
        articles:[],
        page:1
    }

}
async componentDidMount(){
    let url="https://newsapi.org/v2/top-headlines?country=in&category&apiKey=myapikey";
    let data=await fetch(url);
    let pdata=await data.json();
    console.log(pdata)
    this.setState({
        articles:pdata.articles
    })
}
render() {
    return (
        <div className='container my-3'>
           <h1 className='middle' style={{textAlign:'center'}}> Top Headlines</h1><br />
           
           <div className="row ">
           {this.articles.map((el)=>{
                return    <div className="col-md-4" key={el.newsurl}>
                    <h1><NewsItem  title={el.title?el.title:""} description={el.description?el.description.slice(0,88):""}
                     newsimg={el.urlToImage?el.urlToImage:"https://images.wsj.net/im-479937/social"} newsurl={el.url?el.url:""}/></h1>
            </div>

           })}
               
               



           </div>


        </div>
    );
}

}

export default News;

This was my code, im not not understanding why is this giving me the following error

News.js:32 Uncaught TypeError: Cannot read properties of undefined (reading 'map')

PS: This is a project of fetching news from newsapi website and showing it on webapp.

Dragon
  • 27
  • 1
  • 5
  • Does this answer your question? [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Terry Feb 05 '22 at 17:59

1 Answers1

1

articles is not a class variable in your code. It is part of the state. You should use this.state.articles.map in render function.

S. Singh
  • 89
  • 1
  • 9