Stimulus: is disconnecting after every action expected behavior?

Created on 21 Sep 2019  路  3Comments  路  Source: hotwired/stimulus

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')
  }
}

Most helpful comment

You can solve it by annotating your link with the data-turbolinks="false" attribute.

Or making it a <button>

All 3 comments

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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

saneef picture saneef  路  4Comments

gerdriesselmann picture gerdriesselmann  路  3Comments

thooams picture thooams  路  4Comments

dwightwatson picture dwightwatson  路  3Comments

merwok picture merwok  路  4Comments