Search code examples
javascriptreactjsapiundefined

why does its not rendering data from API instead showing this error "Uncaught TypeError: Cannot read properties of undefined (reading 'map' " Help me


In react, I have successfully fetched the data from API in RapidAPI but not working on the web browser, instead showing the above error of undefined map. and even not rendering a single component otherthan that.. if any one could help me ,,

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

export class News extends Component {
  constructor() {
    super();
    this.state = {
      articles: this.articles,
    };
  }
  async componentDidMount() {
    let Url =
      "https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=202bfae039134fdbb014021b4959a6e2";
    let data = await fetch(Url);
    let parseData = await data.json();

    console.log(parseData);
    this.setState = { articles: parseData.articles };
  }
  render() {
    return (
      <div className="container ">
        <h1 className="text-center mb-3">News App | Top Headlines</h1>

        <div className="row">
          {this.state.articles.map((element) => {
            return (
              <div className="col-md-3 my-2 " key={element.description}>
                <NewsItem
                  title={element.title ? element.title : "null"}
                  description={
                    element.description ? element.description : "null"
                  }
                  urlToImage={element.urlToImage ? element.urlToImage : "null"}
                />
              </div>
            );
          })}
        </div>
      </div>
    );
  }
}

export default News;

Solution

  • In Constructor, You are setting this.state.articles to this.articles, there is no articles binded to the class , so this.articles is undefined.

    So in Constructor, Initialise it with empty Array

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

    or in return only map throught the articles , if it has value

         <div className="row">
              // this.state.articles?.map  which only map through the array if it does
              // not have any falsy values
              {this.state.articles?.map((element) => {
                return (
                  <div className="col-md-3 my-2 " key={element.description}>          
                  </div>
                );
              })}
            </div>