Search code examples
javascriptreactjsreact-propsarray.prototype.map

.map is undefined before this.props.action executes


So I am getting an error stating that .map is undefined because I am assuming this.props.action is not finish and therefore makes the .map unable to map anything.

reducer

 case GET_DEALERSHIP_GOAL_TYPE_SUCCESS:
      return Object.assign({}, state, {
        loading: false,
        dealershipGoalType: action.payload.data
      });

mapStateToProps

const mapStateToProps = state => ({
  dealershipGoalType: state.DealerPreferencesReducer.dealershipGoalType,
});

componentDidMount

  componentDidMount = () => {
      this.props.actions.getDealershipGoalType(this.state.prevId, this.state.year)
  };

Render

render = () => {

 let {dealershipGoalType } = this.props;
}

map section

  {dealershipGoalType.map(goal => (
      <option value={goal.type_goal}>
        {goal.label}
      </option>
  ))}

any ideas?


Solution

  • You can assign the initial state of dealershipGoalType to be an empty array, other than that I would suggest you to show an empty text or some sort of loader until you get anything in the dealershipGoalType.

    {
      dealershipGoalType.length > 0 ?
       dealershipGoalType.map(goal => (
        <option value={goal.type_goal}>
         {goal.label}
        </option>
      )
     : <span> There are no listings! </span>
    }