I'm trying to build a react app that communicating with the server to query data from database. I want to display a loading message when the app is fetching data. Here's the code snippet:
class App extends React.Component {
constructor(props) {
super(props)
this.clickHandler = this.clickHandler.bind(this);
this.state = {
isLoading: false,
data: [],
content: ''
}
}
clickHandler() {
this.setState({ isLoading: true });
fetch('url_1')
.then(res => res.json())
.then(data => this.setState({ data: data }, () => {
this.getContentByData() // loading message vanished before content is displayed
}))
.then(() => this.setState({ isLoading: false }));
}
getContentByData() {
fetch(`url_2?data=${this.state.data}`)
.then(res => res.json())
.then(content => this.setState({ content: content }))
}
render() {
return (
<div>
{this.state.isLoading ? <h1>loading</h1>: null}
<h6>{this.state.content}</h6>
<button type="button" onClick={this.clickHandler}>Click Me!</button>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'))
The loading message disappeared before content is displayed. How can I fix this?
You could change your render method to be something like this:
render() {
let content = <Loader />;
if (!this.state.isLoading && this.state.content) {
content = (
<h6>{this.state.content}</h6>
<button type="button" onClick={this.clickHandler}>Click Me!</button>
)
}
return (
<div>
{content}
</div>
)
}
Where Loader is your loader component. Of course it can also be the h1 title or whatever you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With