monkeyjs monkeyjs - 13 days ago 6
React JSX Question

undefined within the react component - but not in action

Have a call to action (backend call) response is some array - getting undefined here - in few other cases where I am mapping over the array I am seeing map of undefined error as well...is componentDidMount right place to put such calls?

I get the response back when I console log in action creator before dispatching...
componentDidMount() {

this.props.fetchData(test, foo);
console.log(this.props.responseData); //getting here undefined
}

function mapStateToProps(state) {
return {
responseData: state.abc.responseData,
};
}

Mycomp.propTypes = {
responseData: React.PropTypes.array,
fetchData: React.PropTypes.func,
};

export default connect(mapStateToProps, actions)(Mycomp);

Answer

It is undefined because the request has not been made at the time you're trying to log the response – it's async.

You can either call the action in here:

componentDidMount() {
  this.props.fetchData(test, foo);
}

componentWillReceiveProps(props) {
  if (props.responseData) { console.log(props.responseData); } // should be getting the data if the request works
}

or define a callback that is executed after the request was successful.

Comments