Requests for a form that submits through ajax multiply with each subsequent submit

57 views Asked by At

I have a form that makes an ajax request, the problem is that every time I click on it, the amount of times it makes that request multiplies.

Now I'm sure it's because of the way I've set up submit-intercept but I don't know how else to do it whilst still encapsulating it as a single component.

I'm using react as my view layer and I've attached a function that contains code to intercept the request and this function is called in both the afterMount callback and the after_update callback; if I don't do this then either the form submit is never intercepted or it only intercepts it once and then just does a normal submit.

Now obviously it's multiplying because those events fire and add an extra submit-handler.

I'm using opal and react.rb so the code might look a little odd.

Here's my function that intercepts the submit action on the form

def set_up_login_form
    puts 'setting up form'
    login_form = Element["#login_form"]
    login_form.on :submit do |event|
        unless login_state == :processing
            event.prevent_default
            username = login_form.find('#username').value
            password = login_form.find('#password').value
            login!
            self.username = username
            self.handle_login_submit({username: username , password: password})
        end 
    end
end

Here are my call backs:

after_mount do
    fix_button #untill materialize.js gets fixed
    set_up_login_form
end

after_update do
    set_up_login_form
end

I was able to reduce the amount of requests made by checking if the component state was already in the middle of a request, whilst this doesn't reduce the amount of submit handlers being added it does stop a good amount from doing anything, but it doesn't stop the actual multiplying of handlers being added.

1

There are 1 answers

0
Thermatix On BEST ANSWER

I don't know why I didn't think of it till a colleague mentioned it but by moving the form to a sub-component I can now run the intercept code on the form components mount which only happens when it's rendered so problem solved!