0

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;

1 Answer 1

2

You have an error when destructuring this.state. const { post } = this.state.post; should be const { post } = this.state;.

EDIT From https://newsapi.org it looks like the structure of the response will be {status: ..., totalArticles: ..., articles: [...]}. So your componentDidMount should be:

componentDidMount() {
  fetch('https://newsapi.org/v2/top-headlines?' +
      'country=us&' +
      'apiKey=GIVEN API KEY')
    .then(response => response.json())
    .then(response => this.setState({post :response.articles}));
}
Sign up to request clarification or add additional context in comments.

8 Comments

Led to another error "Unhandled Rejection (TypeError): this.setstate is not a function"
the correct function is this.setState, not this.setstate
Okay, now theres an error with the map. "TypeError: post.map is not a function".
Your fetch call must be populating state.post with something other than an array when it completes
Have made all the stated corrections and now it's working, but is showing the "else" statement, rather than the news post. You could see that the data was being loaded when you check your browser react developer tool. Reviewed the code several times but cant seem to find any thing.
|

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.