Search code examples
reactjsobject

React - Data not found


I have a main component Resume and a child called Header:

class Resume extends Component {
      constructor(props) {
        super();
        this.state = {
          data: {}
        }
      }
      componentDidMount() {
        this.setState( this.state = data);
      }
      render() {
        return (
          <div className="Resume">
            <Header data={this.state.header} />
            <Skills data={this.state.skills} />
          </div>
        );
      }
    }
    export default Resume;

    class Header extends Component {
      render() {
        return (
          <div className="header">
            <h1>{JSON.stringify(this.props.data.title)}</h1>
          </div>
        );
      }
    }

My simple sample data so far is: 

{
  "header": {
    "title": "Tim Smith's Resume"
  },
  "skills": [
    {"name": "HTML", "duration": 14}
  ]
}

Why am I getting:

TypeError: Cannot read property 'title' of undefined


Solution

    1. No need to use JSON#stringify your title property is already a string.
    2. In your componentDidMount is not like that we are setting state. Try to use

      componentDidMount() const data = {}; // Define data or get it like you want this.setState({ ...data }); }

    3. In your constructor where you initialize your state. You have to do this.state = { header: {}, skills: {} } not what you done.