Stimulus Discourse

Some guidance on using rails-ujs and Rails.ajax in a Stimulus controller

Hi everyone

I need some guidance on whether I am using Rails.ajax correctly, specifically the beforeSend event. Everything in this controller is working perfectly, I would just like to know if this is the most correct way of using Rails.ajax. Here is an example of my controller. I omitted all the surrounding functions and target definitions for brevity.

import ApplicationController from 'support/application_controller'
import Rails                 from 'rails-ujs'

export default class extends ApplicationController {

  startSearch(event) {
    const element = event.currentTarget

    Rails.ajax({
      url:        this.url,
      type:       'GET',
      data:       this.params({ q: element.value }),
      dataType:   'script',
      beforeSend: (xhr, options) => {
        this.renderResults('')
        this.toggleLoader('show')
        return (xhr, options)
      },
      success:    (_response, _status, xhr) => {
        this.renderResults(xhr.response)
      },
      error:      (_response, _status, _xhr) => {},
      complete:   (_xhr, _status) => {
        this.toggleLoader('hide')
      }
    })
  }

}

Personally, I would rather link the success and error callbacks from the html:

<div data-action="ajax:success->my-controller#successHandler" ...></div>