I was trying to fetch the news api but I kept on geeting this errors "" TypeError: Cannot read properties of undefined (reading 'map') "" is there any syntax or I need to add something
import React, { Component } from 'react'
import NewsItem from './NewsItem'
export default class News extends Component {
constructor(){
super();
this.state={
article : this.article
}
}
async componentDidMount(){
let urll = "https://newsapi.org/v2/top-headlines?
country=in&apiKey=6aeca0faebbd45c1a1ec3c463f703ebb";
let data = await fetch(urll);
console.log(data)
let parseData = await data.json() ;
console.log(parseData);
this.setState({article : parseData.articles});
}
render() {
return (
<div className='newcontainer my-5'>
<h1 className='mainheading' >PAHADI PRESS BREAKING NEWS</h1>
{this.state.article.map((e)=>{
return <div key={e.url} >
<NewsItem title={e.title} decription={e.description} imageUrl={e.urlToImage}
newsUrl={e.url}
newsauthor={e.author}/>
</div>
})
}
</div>
)
}
}
CodePudding user response:
As pointed out in Tarek's answer, the article
state is not initialized. The problem arises from the constructor, where you assign {article: this.article}
to the state.
In the constructor, the instance is not yet accessible, it is indeed being constructed, which means that this.article
does not exist yet, thus assigning undefined
to the state.
You can instead assign it a default value, like an empty array: this.state = {article: []}
. This should fix your problem.
componentDidMount
is called after render
, but you populate the state in componentDidMount
and try to access it in render
. this.state.article
will thus always be undefined
for a short period of time, causing the error you mentioned.
CodePudding user response:
Your article
state is not initialized. Make sure that you do that before the component renders.
Instead, you can use the optional chaining ?.
operator when calling the map
method to not cause an error if this.state.article
is nullish (null
or undefined
).
Example: this.state.article?.map(...)