Reputation: 3417
I'm new to Redux. I'm trying to access nested data within my retailer prop. I would like to be able to access the retail 'name' and validate the prop as a string with prototypes. When I try to access the 'name' within render it breaks the app. Is there a better way to do this we Redux.
class MyPage extends React.Component {
componentDidMount() {
const { id } = this.props;
this.props.getRetailer(id);
}
render() {
const { retailer } = this.props.retailer;
const { name } = this.props.retailer && this.props.retailer.retailer;
return (
<div>
<Form
name={name}
/>
</div>
);
}
}
const mapStateToProps = (state) => ({
retailer: state.retailer
});
export default connect(mapStateToProps, {
getRetailer
})(MyPage);
Upvotes: 0
Views: 51
Reputation: 281726
The issue here is that this.props.retailer && this.props.retailer.retailer;
might return null when retailer is not present and hence it will try to resolve name from null which will throw an error
You can use destructuring with fallback like
const { retailer } = this.props.retailer || { retailer: {} };
const { name } = retailer || {};
The above will handle both the cases of this.props.retailer
being null or undefined as well as this.props.retailer.retailer
being null or undefined
Upvotes: 1