Andy Harvey
Andy Harvey

Reputation: 12663

Why is Turbo Stream not updating the DOM?

I am making my first steps to understand Turbo Frames and Turbo Streams.

Following a request, my logs indicate that the relevant turbo_stream.erb file has been rendered, but the DOM remains unchanged.

Can anyone point me in the right direction and help me understand what is going on?

The details are as follows:

I am trying to build a typeahead/ autocomplete field that populates results from the server. When the page loads, I want to pre-populate the list with some common options.

I have a viewcomponent stimulus controller that makes a fetch request.

# typeahead_controller.js
myRequest() {
    return new Request("http://url.to/typeaahead_controller/index", {
      method: "GET",
      headers: {
        Accept: "text/vnd.turbo-stream.html"
      },
      redirect: "manual"
    });
  }

connect() {
  fetch(this.myRequest())
}

the page has an empty list container

#mypage.html.erb 
<ul id="results"></ul>

the controller does not explicitly include a turbostreams responds_to (but I have tested with this and seems to make no difference)

def index
   @ojbs = MyObjects.default_options_scope # I've checked this returns objects, but I'm also testing with a Hello World object (see below) so this should not matter 
end

and I have a turbostream view (I have tested with update, append and other verbs).

# typeahead/index.turbo_stream.erb
<%= turbo_stream.append "results" do %>
    <li>Hello World</li>
<% end %>

When the page is reloaded, the logs seem to indicate that the requests are being handled correctly

Started GET "/typeaheads" 
Processing by TypeaheadsController#index as TURBO_STREAM
Rendering typeahead/index.turbo_stream.erb
Rendered typeahead/index.turbo_stream.erb (Duration: 3.3ms | Allocations: 282)
Completed 200 OK in 57ms

The browser network tab shows the request, but the response is empty (I don't know if it should be?)

Can anyone see anything obviously wrong with this approach? I realise I could probably use a Turbo Frame here, but I was interested to see how/if Turbo Streams could be used. Is Turbo Stream the wrong tool for this problem?

Upvotes: 4

Views: 1935

Answers (1)

Ivan Grishkov
Ivan Grishkov

Reputation: 43

My issue was, that I was trying to update all targets with class css-selector ".invoice-contacts" the same way

to make it work you should use update_all method instead of update

<%= turbo_stream.update_all ".invoice-contacts" do %>
  <%= options_from_collection_for_select(@contacts, :id, :to_s) %>
<% end %>
  = f.select :to_contact_id, {}, {include_blank: true}, { class: "invoice-contacts" } do
    = options_from_collection_for_select(contacts_collection, :id, :to_s)

Upvotes: 1

Related Questions