Ben Rondeau
Ben Rondeau

Reputation: 3053

Reactjs firing AJAX call multiple times a button is clicked (only want 1 per click!)

I have a simple React app that has a form in it and upon the user clicking submit, post the form to a server. Simple enough.

But React is firing the AJAX call multiple times (4-5 usually) in immediate succession, creating all sorts of issues. I don't know why - I assume it has something to do so React's lifecycle, but I am not sure.

I am using axios as a AJAX library, so perhaps the problem is with that library (I think not though).

Here is the method that fires the code:

submitEvent(event) {
event.preventDefault();
const apiQueryString = `api/event?${qs.stringify(this.state)}`;
if (this.state.event_title === undefined) {
  alert('Event title is required!');
} else {
  axios.post(apiQueryString)
      .then((result) => {
        this.state.id = result.data[0];
        store.dispatch({
          type: 'ADD_SINGLE_EVENT',
          event: this.state,
        });
        alert('Success creating event!');
        this.setState({}); // clear out old values
        browserHistory.push('/');
      })
      .catch((error) => {
        console.log(error);
        alert('Error with database! See console for output.');
      });
}

And this is the button that fires this function:

<button onClick={this.submitEvent} className="btn btn-primary">Submit</button>

The entire file's source code is here, and the working page is here.

Thanks for any help you can offer.

Upvotes: 0

Views: 1142

Answers (3)

Hadas Zeilberger
Hadas Zeilberger

Reputation: 761

The problem was with the middleware. In the method that handled this AJAX request on the backend, a new item was being inserted into the database on the successful callback of req.getValidationResult(). This success callback was being called twice, resulting in multiple database inserts.

Upvotes: 1

Zahid Sumon
Zahid Sumon

Reputation: 189

If you have only one button in your form and you don't specify it's type (button/submit) by default it will be a submit button. So it is better to use onSubmit instead of onClick here.

Upvotes: 0

ryandrewjohnson
ryandrewjohnson

Reputation: 555

I would move the submission from the button to the form. Any button inside a form will trigger the form to submit on click, unless that button has type=button attribute. In your case the button click would cause the form to submit, which would then submit a form GET request to your current page.

Your submitEvent method is already preventing the default event, which should stop the native form submit from happening.

<form onSubmit={submitEvent}>
  // this button is inside form so clicking it will trigger form submit
  <button className="btn btn-primary">Submit</button>
</form>

Upvotes: 0

Related Questions