Shpongle
Shpongle

Reputation: 31

TypeError: Cannot read properties of undefined (reading 'id') in React

I have built a website but I encounter a problem when I press button "Load More" after 3 times. It gives me an error of "TypeError: Cannot read properties of undefined (reading 'id')"...I guess something wrong with slice and map function! P.S. I tried to call "id" to other component but in vain!

class PostsList extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      posts: [],
      visible: 3,
      error: false
    };

    this.loadMore = this.loadMore.bind(this);
  }

  loadMore() {
    this.setState((prev) => {
      return {visible: prev.visible + 3};
    });
  }

  componentDidMount() {
    fetch("https://jsonplaceholder.typicode.com/posts").then(
      res => res.json()
    ).then(res => {
      this.setState({
        posts: res
      });
    }).catch(error => {
      console.error(error);
      this.setState({
        error: true
      });
    });
  }

  render() {
    const { classes } = this.props;

    return (
      <div className={classes.section}>
        <h2 className={classes.title}>Latest news</h2>
        <div>
          <GridContainer>
            {
              this.state.posts.slice(0, this.state.visible).map((post, i) => {
               return (
                  <PostCard key={i}
                  id={posts[i].id}
                  date={posts[i].date} 
                  fbimg={posts[i].fbimg} 
                  description={posts[i].description} 
                  fbpost={posts[i].fbpost}
                  />
                );
              })
            } 
          </GridContainer> 
           <GridContainer>
            <GridItem>
            {this.state.visible < this.state.posts.length &&
              <Button 
                color="info"
                onClick={this.loadMore} 
              >
              Load more
              </Button>
            }
            </GridItem>
          </GridContainer>
      </div>
    </div>
    );
  }
}

Thank you in advance!!!

Upvotes: 0

Views: 1975

Answers (1)

larz
larz

Reputation: 5766

posts is not defined inside your render function. Did you mean this.state.posts?

Also, there's no need to use the index to access posts when you already have the single post available from your map function. So change posts[i].id to post.id.

Upvotes: 2

Related Questions