-4

This is my and i am trying to fetch api and show the result in my next react component but if i can set the state in the componetmountfunction it can cause the error. !this.state.articles.map is not a function!. Please solve this problem and also mention the reason of error because i am beginner in react.


import React, { Component } from "react";
import Newscompo from "./Newscompo";
class App extends Component {
constructor(props) {
super(props);
console.log('this is constructor');
// Set initial state
this.state = { articles: '' };

    // // Binding this keyword
    this.componentDidMount = this.componentDidMount.bind(this);

}
async componentDidMount() {
// Changing state
console.log('fetch the api now');

    let url =
      "https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=9c1cd38&pageSize=1";
    let data = await fetch(url);
    let parseData = await data.json();
    console.log('The api is');
    // console.log(parseData)
    this.setState({ articles: parseData.articles });

}
render() {
return (
\<div\>
\<div className="container  my-5"\>
\<div className="row "\>

<h2>Pratice-Headlines</h2>
{this.state.articles.map((obj)=\>{
return \
\
\
})}

          </div>
        </div>
      </div>
    );

}
}

export default App;

IN the Console the error is....


Uncaught TypeError: this.state.articles.map is not a function
render Practicstate.js:82
React 12
workLoop scheduler.development.js:266
flushWork scheduler.development.js:239
performWorkUntilDeadline scheduler.development.js:533
js scheduler.development.js:571
js scheduler.development.js:633
factory react refresh:6
Webpack 24
Practicstate.js:82

Please anyone solve this error and also mention that what mistake is taken by me! 
Rick Kim
  • 1
  • 2

1 Answers1

0

You are declaring articles initially as a string. React calls the lifecycle methods in the following order:

constructor()
getDerivedStateFromProps()
render()
componentDidMount()

In your case, in the render method, map function throws an error because you declared articles as a string. To fix this, declare articles as an empty array.

constructor(props) {
super(props);
console.log('this is constructor');
// Set initial state
this.state = { articles: [] };

    // // Binding this keyword
    this.componentDidMount = this.componentDidMount.bind(this);

}
the.marolie
  • 1,032
  • 2
  • 7
  • 14