Reputation: 47
In componentWillMount()
i call fetch
method to get data. But when fetch
not loaded. This component was render
.
How to fix it.? how to fetch loaded before render()
Upvotes: 0
Views: 253
Reputation: 17608
You can't. When you getting data and feeding your component generally you need to check if there is any data. If there is not, either render nothing or render something like "No data." or show a spinner there. Use componentDidMount for that.
class App extends Component {
state = {
data: "",
}
componentDidMount() {
this.fetchData();
}
fetchData() {
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => response.json())
.then(json => this.setState( {data: json}));
}
render() {
return (
<div>
{ this.state.data ? <p>{this.state.data.title}</p>: "No data"}
</div>
);
}
}
Upvotes: 1