Search code examples
htmlreactjsapiserverloader

How to show loader while API status is pending in React JS


I have to show loader while my API request is pending. I try but it's not working. So how to do this.

this.props.showLoader();
        ajax(config)
            .then((response) => {
                let data;
                this.props.hideLoader();
                data = response.data;
                data[this.props.moduleName.storeVarName + "MediaCost"] = response.data.totalCampaignCost ? response.data.totalCampaignCost : 0;
                this.props.updateCampaignData(data);
            }).catch((error) => {
                this._errorHandler(error);
                this.props.hideLoader();
            });

Solution

  • the informatiom provided by you is not enough, though I am sharing an example to show loader while making http request:

    const Loader = () => <div>Loading...</div>;
    
    class MyComponent extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          loading: false,
        };
      }
    
      hideLoader = () => {
        this.setState({ loading: false });
      }
    
      showLoader = () => {
        this.setState({ loading: true });
      }
    
      fetchInfo = () => {
        const _this = this;
        this.showLoader();
        ajax(config)
          .then((response) => {
            // do whatever you want with success response
            _this.hideLoader();
          }).catch((error) => {
            // do whatever you want with error response
            _this.hideLoader();
          });
      }
    
      render() {
        return (
          <div>
            <button onClick={this.fetchInfo} />
            {(this.state.loading) ? <Loader /> : null}
          </div>
        );
      }
    }