Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - show loading message before fetched data is rendered

Tags:

reactjs

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?

like image 232
Eric Hung Avatar asked Mar 19 '26 09:03

Eric Hung


1 Answers

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.

like image 157
Sagi Rika Avatar answered Mar 22 '26 12:03

Sagi Rika