Stop users from double sending API requests in React.js?

Answered
nick asked this question 21 days ago
nick 21 days ago

In my React.js application, an API request is sent when a user clicks on a button via an onClick() event handler:

<button onClick={this.submitRequest}>
  Submit
</button>

When this button is clicked, a request is sent to my REST API using the submitRequest() function.

How do I stop a user from sending more than one request at a time?

2 suggested answers
suparman21 13 days ago

You can add a this.state.loading boolean value to your this.state object. When a request is in progress, set that value to true and don't allow a request to be made unless this.state.loading === false.

Your this.state object could look like this:

constructor(props) {
  super(props)
  this.state = {
    loading: false
  }
}

Then, update your submitRequest() function to something similar to this:

submitRequest() {
  // stop the function from continuing if this.state.loading === true
  if (this.state.loading) return

  // set the loading state to true
  this.setState({loading: true})

  // make API request

  // after the API request is done, set the loading state back to false
  this.setState({loading: false})
}

This will ensure that a user is only sending one request at a time. And, therefore, stops any double send problems that may occur.

0 replies
yaboy01 13 days ago · Edited

You can set your button's disabled attribute to true while the request is being made and set it back to false after it has finished.

Here's what the code for that would look like:

export default class extends Component {
  constructor(props) {
    super(props)
    this.state = {
      disabled: false
    }
  }

  submitRequest = () => {
    if (this.state.disabled) return

    this.setState({disabled: true})

    // make API request here

    // call this when the API request completes
    this.setState({disabled: false})
  }

  render() {
    return (
      <button
        onClick={this.submitRequest}
        disabled={this.state.disabled}
      >
        Submit
      </button>
    )
  }
}

Using this React.js code, the button will be unusable and un-clickable while the API request is being made. And will become available again once the request is complete.

As a result, a user will only be able to send one request at a time.

0 replies
Answered