I have a stimulus controller that has a button inside of it with a stimulus action associated. When I click the button, it invokes a method in a controller that copies the html of a form I have inside of a template (Also marked with a data-target value) into a another div (again, also marked a data-target value). It works, but as soon you see the form, it immediately disappears.
After adding some console log statements on both the disconnect() and connect() methods, I see that as soon as I click the button, the controller disconnects and then reconnects, which is what I assume to be the culprit behind my immediately disappearing form.
Is that supposed to happen? I hope that isn't normal behavior. It's a really weird bug. Here's my code:
<%= link_to fa_icon('plus'),
'#',
class: 'btn btn-sm btn-success',
data: { action: 'tasklist#newTask' } %>
<div class="card-body text-primary">
<template data-target='tasklist.taskFormTemplate'>
<%= simple_form_for Task.new, url: '', remote: true do |f| %>
<%= f.date_field :start_date %>
<%= f.date_field :end_date %>
<% end %>
</template>
<div data-target='tasklist.taskFormContainer'>
</div>
</div>
here is my controller:
import { Controller } from "stimulus"
export default class extends Controller {
static targets = [ 'taskFormTemplate', 'taskFormContainer' ]
newTask() {
this.taskFormContainerTarget.innerHTML = this.taskFormTemplateTarget.innerHTML
}
connect() {
console.log('connected')
}
disconnect() {
console.log('disconnect')
}
}
My hunch is that you're seeing an unexpected Turbolinks redirect.
Turbolinks currently reloads the page on same-page anchor links, which your link with the newTask action is. It looks like the form disappears but it's actually the page being reloaded.
You can solve it by annotating your link with the data-turbolinks="false" attribute.
You can solve it by annotating your link with the data-turbolinks="false" attribute.
Or making it a <button>
You can solve it by annotating your link with the
data-turbolinks="false"attribute.
Or making it a
<button>
I'd go the <button> route, but 馃憤 to either option.
Most helpful comment
Or making it a
<button>