rails / request.js

MIT License
389 stars 28 forks source link

Can shorthand methods be used not-async? #69

Closed nimmolo closed 9 months ago

nimmolo commented 9 months ago

To integrate a requestjs call with a complicated existing form on my site, I'd like to execute a post fetch non-async. Can the shorthand methods be used this way?

post(url, { body: _formData, responseKind: "json" }).then((response) => {
  if (response.ok) {
    ...
  } else {
    ...
  }
}

It doesn't seem to work. Maybe there's a better way to do it.

I'm using requestjs post in a stimulus controller for a form. It interrupts submit to upload files that have been added to a multi-file field, and add attachment records (very old app, not using ActiveStorage). These attachments will be associated with the "main" record that gets created when the form is submitted.

My form waits to submit until this post request has been called x number of times - as many times as there are file "attachments" - and a boolean flag in the Stimulus controller has been cleared. Each post request is adding a new "attachment" record that will be associated with the "main" record that gets created on submit.

When the post is async, the form submits prematurely; the attachments do not exist yet, and they are not associated with the "main" record, or the "main" record is created twice - once without attachments, and once with.

marcelolx commented 9 months ago

It doesn't seem to work. Maybe there's a better way to do it.

Could you explain more about what doesn't seem to work? I think post(...).then((response) => {}) should work, I could be mistaken though

It is hard to grasp what could be wrong, an example app would be very helpful (that demonstrates that the post(...).then version doesn't work as it is supposed to

nimmolo commented 9 months ago

@marcelolx it was a different problem causing the premature submit. I checked everything for hours before posting this, but i missed something!!

Sorry, thanks for confirming it should work with .then((response) =>{})

marcelolx commented 9 months ago

Perfect, glad you figured it out!