How can I display a spinner in a React App?

Viewed 154

I have a React App and I want to show a spinner when processing will take some time to complete, for example an API request, or even lengthy setting of state. I have tried a callback such as:

                this.setState({
                    showSpinner: true,
                }, () =>
                    this.APIgiveMeTheWorld().then(
                        this.setState({
                            showSpinner: false,
                        })
                    ));

and async function with:

                await this.setState({
                    showSpinner: true,
                });
                this.APIgiveMeTheWorld().then(
                    await this.setState({
                        showSpinner: false,
                    })
                );

But at no discernible point does state show showSpinner as being true (therefore my spinner never appears). What is the best way to implement this kind of functionality.

3 Answers

What you can do is to show the Spinner as long the showSpinner state is false and hide it when It became false

{ !showSpinner? <SpinnerComponent /> : <ResultShower /> }

And in your component you can load your data from an API in the componentWillMount lifeCycle and when the loading completed and you have data back from the API's Call you can update the showSpinner state to false, which will automatically hide the SpinnerComponent and show whatever else you want to show.

componentWillMount() {
    loadData().then((data) => {

        // Here I consider get data from from you API request

        this.setState({
           data,
           showSpinner: false
        });
    })
}

I see you have passed result of setState in call back then. Did you try:

this.setState({
    showSpinner: true,
}, () =>
    //should pass a call back function to call right after api return.
    this.APIgiveMeTheWorld().then(r => {
        this.setState({
            showSpinner: false,
        })
    }));

The problem is with my API function resolving instantaneously.

Related