首页 > 解决方案 > 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();
            });

标签: htmlreactjsapiserverloader

解决方案


您提供的信息还不够,尽管我正在分享一个示例以在发出 http 请求时显示加载程序:

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>
    );
  }
}


推荐阅读