1-click unsubscribe - using stimulusjs to auto-submit a link_to ... method: :post

Wondering what would be a good way to use stimulus with to submit the form autogenerated by a link_to with a method: :post.

The use case is a 1-click unsubscribe: click on unsubscription link in email footer -> “new” unsubscription page, auto-redirect via post to the “update” action.

I considered updating the subscription directly via the link but triggering changes via “get” goes against the protocol of HTTP verbs and could be triggered by browser prefetch.

So, the stimulus controller will check if the request is made by a browser, is visible in an active tab, and if yes, will redirect to the update action. Otherwise, it will fall back on the “new” page with a link to confirm the unsubscription.

The code in unsubscriptions/new.slim:

= link_to "Confirm unsubscription", confirm_unsubscription_path(email_address: params[:email_address]), method: :post

When given :post, the Rails link_to helper creates a form. Ideally the stimulus controller would post that form. In a less attractive scenario I’d have to manually create a form everywhere I use such a flow.

Is there a way for me to use a stimulus controller on the link_to helper and initiate the post action?

Answering my own question - this was simpler than I expected. The target data element is on the link_to helper.

If the visibility api is unsupported or the browser is pre-fetching, this will fall back to showing the page with the link. Exactly what I needed.

export default class extends Controller {
  static targets = ["item"]

  connect() {
   // console.log(this.itemTarget)

    if ( document.visibilityState == 'visible') {
      this.itemTarget.click()
    }
  }

}