aarkerio
aarkerio

Reputation: 2354

React: props populated with componentWillMount and Redux

So I have this loop in my render:

      {this.props.OneTestArrayProp.questions.map((q, i) =>
        <div key={i} className="questions_div">
          <div>Question: {q.question}</div>
        <div>
      )}

The this.props.OneTestArrayProp is loaded this way:

componentWillMount() {
  if ( ! this.props.OneTestArrayProp.length ) {
     this.props.dispatch(fetchOneTest(test_id));
  }
}

But I'm getting:

Error: "this.props.OneTestArrayProp.questions.map" undefined

the error appears just for a second and then it disappears when Redux load the data. Of course the root of the problem is that half second when this.props.OneTestArrayProp is populated by the middleware thunk.

There is a way to indicate to React to "wait" before it does the render?

SOLVED

The solution provided by Red Mercury works pretty well, however I coded a more "redux-like" approach adding a new Array:

this.props.QuestionsArrayProp = [];

and linking it with its reducer:

  QuestionsArrayProp:  state.rootReducer.questions_reducer.QuestionsTestArrayProp

That way I get an initial, empty but existent array.

Upvotes: 1

Views: 797

Answers (1)

Red Mercury
Red Mercury

Reputation: 4310

Check if it exists before mapping over its questions

  {this.props.OneTestArrayProp && 
   this.props.OneTestArrayProp.questions.map((q, i) =>
    <div key={i} className="questions_div">
      <div>Question: {q.question}</div>
    <div>
  )}

If this.props.OneTestArrayProp is undefined the expression will short-circuit and the map will never be executed

Upvotes: 4

Related Questions