React: How to check if received props are undefined?
Simple solution will be:
<AuthorForm
author={this.state.author || {firstName:'', lastName:'', id:''}}
...
/>
And remove the componentWillReceiveProps
method from child component.
Better approach will be:
1- Either assign the initial value of author
in state as:
this.state = {
author: {firstName:'', lastName:'', id:''}
}
2- Or inside render method of child component, write it like this:
render(){
const {firstName='', lastName='', id=''} = this.props.author || {};
return(....)
}
And use firstName, lastName, id
directly instead of this.props.
Issues in your code:
1- It should be nextProps.author
instead of nextProps.state.author
in componentWillReceiveProps
lifecycle method.
2- Props are read-only, Whether you declare a component as a function or a class, it must never modify its own props. You are trying to change the value in componentWillReceiveProps
.
Your error message is;
Cannot read property 'author' of undefined
It is actually not author
that is undefined but nextProps.state
. nextProps
is an object containing the contents of only the props.
The other problem here is that componentWillReceiveProps()
is not called when when mounting, thus if props.author
is initially undefined then that error handling won't work. Mayank Shukla has a good answer, however that requires you to have a constructor like so;
constructor(props) {
super(props);
this.state = {
author: this.props.author,
};
}
Since props cannot be updated, it makes more sense to put it in the state so that it can be in the future. If you need to receive prop updates, use setState()
in componentWillUpdate()
Another, more long winded solution would be to make author
a required prop, and not attempt to create that component until the necessary props exist. This is also better practice.
AuthorForm.propTypes = {
author: PropTypes.string.isRequired,
};