Im building a react website which will fetch data from the newsapi and display on cards. On checking whether there's a length in which after, it will display or display an alternative response, am getting this error. "TypeError: Cannot read property 'length' of undefined"
Heres whats ive coded:
import React, { Component } from 'react';
class Cards extends Component {
constructor () {
super();
this.state = {
post: [
{
author:"",
discription:"",
publishedAt:"",
title:"",
urlToImage:""
}
]
};
}
componentDidMount() {
fetch('https://newsapi.org/v2/top-headlines?' +
'country=us&' +
'apiKey=GIVEN API KEY')
.then(response => response.json())
.then(response => this.setState({post :response}));
}
render() {
const { post } = this.state;
const postlist = post.length ? (
post.map(post => {
return (
<div>
<div class="container card mb-3">
<div class="row no-gutters">
<div class="col-md-4">
<img src={post.urlToImage} class="card-img" alt="..."/>
</div>
<div class="col-md-8">
<div class="card-body">
<h5 class="card-title">{post.title}</h5>
<p class="card-text">{post.description}</p>
<div class="row">
<p class="card-text col-6"><small class="text-muted">{post.author}</small></p>
<p class="card-text col-6"><small class="text-muted">{post.publishedAt}</small></p>
</div>
</div>
</div>
</div>
</div>
</div>
);
})
)
: (
<div class="center">No post yet!</div>
);
return (
<div class="container">
<h2>Latest News</h2>
{postlist}
</div>
);
}
}
export default Cards;