Reputation: 659
I receive the "Uncaught TypeError: Cannot read property 'data' of null" error in the console when I'm loading up my page. In the constructor I call an external api for data with axios using redux-promise, then I pass props down to a stateless component (TranslationDetailBox). The data arrives, and the child component will receive the props shortly (page looks ok), but first the error message appears.
this.props.translation is empty before the api call, and rendering happens before the state is updated with the external data. I believe this is the issue, but I have no clue on how to solve it.
class TranslationDetail extends Component {
constructor(props){
super(props);
this.props.fetchTrans(this.props.params.id);
}
render() {
return (
<div className="container">
<TranslationDetailBox text={this.props.translation.data.tech}/>
<TranslationDetailBox text={this.props.translation.data.en}/>
</div>
);
}
}
function mapState(state) {
const { translation } = state;
return { translation };
}
...
Upvotes: 2
Views: 1237
Reputation: 2894
I find this to be a good use case for conditional rendering.
Your render could check to see whether the data has loaded or not and if not, render something indicating it is still loading.
A simple implementation could be:
render() {
return (
!this.props.data ?
<div>Loading...</div>
:
<div>{this.props.data}</div>
)
}
Upvotes: 6
Reputation: 36511
You could set defaultProps
:
TranslationDetail.defaultProps = {
translation: {
data: {}
}
};
Upvotes: 3