DEV Community

Cover image for Using Rails UJS Confirmations in Stimulus and StimulusReflex
Matt Buck
Matt Buck

Posted on • Edited on

Using Rails UJS Confirmations in Stimulus and StimulusReflex

One of the many benefits of using the fantastic StimulusReflex has been a return to using the conventions of Rails UJS. Simply appending a data attribute to an element to have it automatically disable itself during an interaction is the type of magic that reminds me of first getting started with Rails.

If you need to add a confirmation step to an interaction, which is a common pattern if a user is trying to destroy an object, you can make use of the data-confirm attribute:

<button data-confirm="Are you sure you want to remove this context?">
  <%= render_svg 'icons/custom/remove' %>
</button>
Enter fullscreen mode Exit fullscreen mode

If you try to use data-confirm with Stimulus or StimulusReflex, you'll find out that data-confirm is not supported out-of-the-box - which makes sense. In order to use it along with data-action or data-reflex, you can simply listen for the confirm:complete event (instead of click) that is triggered by rails-ujs when the user accepts the confirmation modal:

<button data-reflex-dataset="combined"
        data-confirm="Are you sure you want to remove this context?"
        data-reflex="confirm:complete->Context#remove_context">
  <%= render_svg 'icons/custom/remove' %>
</button>
Enter fullscreen mode Exit fullscreen mode
// When confirmation accepted, delete the block.
this.element.addEventListener('confirm:complete', (event) => {
  this.stimulate('ScriptEditor#delete_context', event.target)
})
Enter fullscreen mode Exit fullscreen mode

user accepting a confirmation modal

Now, the action specified by data-action or data-reflex will only be triggered if the user accepts the confirmation dialog. This allows us to easily add a confirmation step to any Stimulus or StimulusReflex interaction.


I ran across this issue while building Voxable, a conversation design platform. If you're building chatbots or voice applications, I hope you'll check it out!

Top comments (3)

Collapse
 
coderberry profile image
Eric Berry

Thank you!

Collapse
 
leo123 profile image
Leo • Edited

For me, it gets called whether the user accepts or not.

Collapse
 
techpeace profile image
Matt Buck

I updated this post a while back when I also caught the error but forgot to say thank you. 🙌