itsame-ebp
itsame-ebp

Reputation: 63

React can't render state property

I keep getting a typeerror: cannot read property ... I'm setting the state to a JSON object from a fetch response. The String and Date properties of the object seem to be rendering fine but the Array and Number properties keep getting type errors.

class ViewPost extends Component {
    state = {
      post: {}
    }

    constructor(props) {
      super(props);
      this.setPostState = this.setPostState.bind(this);
    }

    componentWillMount() {
      this.setPostState();
    }

    setPostState() {
      let postTitle = this.props.match.params.id;
      fetch('/posts/getpost', {
        method: 'post',
        headers: {
          'Accept': 'application/json, text/plain, */*',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          title: postTitle
        })
      })
      .then(res => res.json())
      .then(post => this.setState({ post }))
    }

    render() {
      return (
        <div className="Post">
          <div className="card">
            <img className="img-fluid" src="/img/darkstockphoto.jpg" alt="Post"/>
            <div className="card-body">
              <h4 className="card-title">{this.state.post.title}</h4>
              <p className="card-text">{this.state.post.author}</p>
              <p className="card-text">{this.state.post.date}</p>
              <p className="card-text">{this.state.post.body}</p>
            </div>
          </div>
          <hr />
          {this.state.post.comments && this.state.post.comments.map(comment => (
            <div key={comment.author + comment.date} className="card card-body">
              <h4 className="card-title">{comment.title}</h4>
            </div>
          ))}
        </div>
     );
   }
}

export default ViewPost;

Upvotes: 0

Views: 799

Answers (1)

Syed
Syed

Reputation: 269

setState is asynchronous, so you need to handle your this.state.post like this:

render() {

  if (this.state.post) {
    return (<div className="Post">
      <div className="card">
        <img className="img-fluid" src="/img/darkstockphoto.jpg" alt="Post"/>
        <div className="card-body">
          <h4 className="card-title">{this.state.post.title}</h4>
          <p className="card-text">{this.state.post.author}</p>
          <p className="card-text">{this.state.post.date}</p>
          <p className="card-text">{this.state.post.body}</p>
        </div>
      </div>
      <hr/> {
        this.state.post.comments && this.state.post.comments.map(comment => (<div key={comment.author + comment.date} className="card card-body">
          <h4 className="card-title">{comment.title}</h4>
        </div>))
      }
    </div>);
  }

  return null;
}

Upvotes: 3

Related Questions