Stimulus Discourse

Pairing data-action with data-confirm in rails?

I’m using rails with stimulus-js and rails has a built-in ‘data-confirm’ parameter for form_tag. I’m having issue pairing those two together…

I have a list of products that clients can ‘remove’, I do it through ajax, but I also use data-confirm, since it’s a destructive action.

Example code:

<script src="https://unpkg.com/stimulus/dist/stimulus.umd.js"></script>

<script>
  (() => {
    const application = Stimulus.Application.start()

    application.register("product-listing", class extends Stimulus.Controller {
      static get targets() {
        return [ "product" ]
      }

      remove() {
        this.productTarget.classList.add('is-invisible')
      }
    })
  })()
</script>

<div class='box' data-controller='product-listing' data-target='product'>
        <div class="level-item" >
              <%= form_tag "#{store_path(store)}/products/#{product[0]}", 'data-action':'product-listing#remove', method: :delete, remote: true, 'data-confirm': "This will remove product from store. You want to continue?" do |f| %>
              <%= button_tag(class: 'level-item button is-small is-danger is-outlined', type: 'submit', data: { disable_with: '<span>Removing...</span>'.html_safe}) do %>
              <span class='icon'>
                <i class='fa fa-trash-o'></i>
              </span>
              <span> Remove </span>
              <% end %>
              <% end %>
         </div>
</div>

The problem is, that Product disappears before user confirms his action.

I’m probably missing something trivial here. But I’ve been through google and documentation couple of times and not sure how to solve this correctly.

Maybe I should hook up to ajax call, not to the click?

Usually, the data-confirm attribute is attached to the button or link, not the form itself. Have you tried that? It should prevent the form from submitting (and your action from being called) until the user has confirmed.

Hey @kaspermeyer

Thanks for your suggestion. I actually solved this already, I got an idea based on your answer in another thread:

Now I remove form from page only after ‘ajax:success’ happened. And that completely solves my issue!

1 Like