2

I am working on search filter in ReactJS and I face a problem. Problem is about when User does some search and wants to click on next (because I have pagination in app) then the User will click twice to load other pages of data.

I need to avoid this behaviour: I mean when user does single click on next it should be "load a data" instead of "double click".

I am new to ReactJS, please expert help me

Code

    btnClick() {
        const { Item,skip , filtered, data } = this.state
        if(filtered.length>0 || !data.length ){
          window.alert("Hello,")
          this.setState({
            filtered:[],
            skip:0
          },()=>this.getData());
          return false
        }else {
          window.alert("Hello , Dear")
        this.setState(
          {
            Item,
            skip: skip + pageSize
          },
          () => this.getData()
        );}

      }
timur
  • 14,239
  • 2
  • 11
  • 32
Andrew
  • 93
  • 3
  • 12

1 Answers1

5

You can have a isLoading state and set the disabled prop on the button when in this state which will not allow the button to be clicked again while the data is being fetched.

 btnClick() {
   const {
     Item,
     skip,
     filtered,
     data
   } = this.state;
   
   if (filtered.length > 0 || !data.length) {
     window.alert("Hello,")
     this.setState({
       filtered: [],
       skip: 0
     }, () => this.fetchData());
     return false
     
   } else {
     window.alert("Hello , Dear")
     this.setState({
         Item,
         skip: skip + pageSize
       },
       () => this.fetchData()
     );
   }
 }
 
 fetchData() = async() => {
     this.setState({ isLoading: true });
     
     await this.getData();
     
     this.setState({ isLoading: false });
 }
 
 render() {
        const {
      isLoading
    } = this.state;
    
    const buttonProps = isLoading ? { disabled: true} ? {};
    
    return (
      <button onClick={this.btnClick} { ...buttonProps }>
            Click to fetch
      </button>
    );
 }
Sushanth --
  • 55,259
  • 9
  • 66
  • 105