Reputation: 287
Given my code:
class Example extends Components {
constructor(props) {
super(props)
}
componentDidMount() {
//fetch data
}
render() {
const {obj} = this.props;
if(R.isEmpty(obj)) {
return null;
}
return (<div>{obj.name}</div>)
}
}
the obj
is retrieved from server. so for the initial render, obj
is empty. If I don't return null, obj.name
would report error
so is it a good practise to return null
before I get response from server? thanks
Upvotes: 3
Views: 2148
Reputation: 7330
so is it a good practice to return null before I get a response from the server?
It is ok to do it but also depends on a situation. For example in some case, you can avoid rendering the component at all like this:
class ParentComp extends Component {
render() {
return (
<div>
{!R.isEmpty(obj) && <Example obj={obj}/>}
</div>
);
}
}
Upvotes: 0
Reputation: 104369
Yes, that is the proper way. If don't want to render
anything return null
.
One more thing if you want to wait for response
and hold the rendering
until that, you can return
this also:
if(R.isEmpty(obj)) {
return <div>Loading...</div>
}
By this way user will come to know that something is going on, some kind of data is being fetch from server
, this is more intuitive i think.
Upvotes: 3