Reputation: 773
So my react class calls to a json response and then renders.
But as it stands, the class will render on initial load then render again when response has come back.
To get around this I have do this -
componentDidMount: function() {
axios.get.......
.then(res => {
const jobs = res.data;
this.setState({ jobs });
});
},
render: function () {
if (Object.keys(this.state.jobs).length == 0)
{
}
else {
return (
<div>
{this.state.jobs.data.map(function (ob) {
return <li key={ob.id}>{ob.name}</li>
})}
</div>
)
}
return null;
}
});
Is there a nicer way to do this? without using an if statement?
Upvotes: 0
Views: 448
Reputation: 2803
React always has to render in the initial load. So you just need to render null like you already did. Code wise, maybe you can write
return this.state.jobs.data ? <YourTemplate /> : null;
which is cleaner.
Upvotes: 2