2

I have a simple modal where I writte some data and submit to database. I'm trying to implement a simple loading on the button, so the user receives feedback. Unfortunately, this isn't working.

constructor(props) {
super(props);
 this.state = {
    isLoading: false, 
    show: false,
    list: []
    }
 }

onSubmit = async event => {
  ref.onSnapshot(async doc => {
    if (doc.data().status === 'accepted') {
      const list = await this.get(name, age, id);
      this.setState(prevState => ({
        isLoading: !prevState.isLoading, // this doesn't work
        list: list,
        show: false // state for a modal
      }, () => console.log('loading on submit', this.state.isLoading)))
    }
   }
 }

<button
  onClick={this.onSubmit}
  disabled={this.state.isLoading ? true : false}>
  {this.state.isLoading ? 'Loading...' : 'OK'}
</button>

Thank you! :)

2 Answers 2

3

You want to set isLoading to true before you get your data, and then set isLoading to false when the asynchronous request is complete.

Example

function getList() {
  return new Promise(function(resolve) {
    setTimeout(() => resolve([1, 2, 3]), 1000);
  });
}

class App extends React.Component {
  state = {
    isLoading: false,
    show: false,
    list: []
  };

  onSubmit = event => {
    this.setState({ isLoading: true });
    getList().then(list => {
      this.setState({
        isLoading: false,
        list,
        show: false
      });
    });
  };

  render() {
    return (
      <button
        onClick={this.onSubmit}
        disabled={this.state.isLoading}
      >
        {this.state.isLoading ? "Loading..." : "OK"}
      </button>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>

Sign up to request clarification or add additional context in comments.

Comments

1

trigger loading true before await call like below code.

   onSubmit = async event => {
   ref.onSnapshot(async doc => {
   if (doc.data().status === 'accepted') {
     this.setState({
       isLoading : true
     })
     const list = await this.get(name, age, id);
     this.setState(prevState => ({
       isLoading: false, 
       list: list,
       show: false // state for a modal
     }, () => console.log('loading on submit', this.state.isLoading)))
   }
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.