0

I am trying to learn react js. When I called my first api in react js i am getting error Unhandled Rejection (TypeError): this.setState is not a function. I tired to figure out this error. Please review my code and let me know what i am doing wrong. Thanks

import React from 'react';
class Post extends React.Component {
  constructor(props){
    super(props);
    this.setState = {posts: []}
  }
  componentDidMount(){
    this.getPost();
  }
  getPost(){
    fetch('https://jsonplaceholder.typicode.com/posts')
    .then(response => response.json())
    .then(({data}) => this.setState({ posts: data }));
  }
  render(){
   return (
         <div>
           <h2>Post</h2>
         </div>
      )
  }
}
export default Post;
Sandeep
  • 973
  • 2
  • 13
  • 22

1 Answers1

3

You had a typo in your state initialization. It should be this.state.

Change

constructor(props){
    super(props);
    this.setState = {posts: []}
}

to

constructor(props){
    super(props);
    this.state = {posts: []}
}
nithinpp
  • 1,785
  • 12
  • 24