Search code examples
javascriptreactjsreduxrenderlifecycle

React Redux - Error on render because expecting props that didn't arrive yet


After fetching the data from an API, and putting that data on the Redux state, I'm using a helper function in mapStatetoProps to select and modify part of that data and pass it modified to the props.

So without the rendering I can see in the console.log that everything goes as it should.

  1. Empty props: this.props.pageContent = {}
  2. The data fetch and mapped to props: this.props.pageContent = { pageSection: [{something here that I don't want}, {}, {}...] }
  3. The data as I want it selected and passed to the props: this.props.pageContent = { pageSection: [{card: 'my Data'}, {}, {}...] }

but when I pass some propsto a component it throws an error because those props that I'm trying to pass haven't arrived yet to this.props (in this case card.cardTitle)

This is my code so far:

class Page extends Component {
  componentWillMount() {
    this.props.fetchPageContent();
  }
  render() {
    console.log(this.props.pageContent)
        if (!this.props.pageContent.pageSection[0].card) return null;
    return (
      <div>
        <PageSection
          introSectionCardTitle={ this.props.pageContent.pageSection[0].card.cardTitle}
          introSectionCardContent={ this.props.pageContent.pageSection[0].card.cardContent}
        />
      </div>
    );
  }

Any ideas? before the return I tried to have an if statement with diferent options, but the error keeps the same: TypeError: Cannot read property '0' of undefined


Solution

  • You have a problem here if (!this.props.pageContent.pageSection[0].card)

    replace

    if (!this.props.pageContent.pageSection[0].card)

    with

    if(this.props.pageContent && this.props.pageContent.pageSection && this.props.pageContent.pageSection[0].card)

    Because you are not sure that your props has pageContent and you are also not sure that pageSection exist, because before setting the props pageContent is undefined and you are trying to access an object inside it and then find element inside an array

    Try the updated code below:

    class Page extends Component {
          componentWillMount() {
            this.props.fetchPageContent();
          }
          render() {
            console.log(this.props.pageContent)
            if(this.props.pageContent && this.props.pageContent.pageSection && this.props.pageContent.pageSection[0].card)
            {
                return (
                  <div>
                    <PageSection
                      introSectionCardTitle={ this.props.pageContent.pageSection[0].card.cardTitle}
                      introSectionCardContent={ this.props.pageContent.pageSection[0].card.cardContent}
                    />
                  </div>
                );
            }
            else
            {
                return (<div></div>);
            }
    
          }