bolom
April 29, 2021, 4:56pm
1
Hey guys.
I am using hotwired/turbo-rails": “^7.0.0-beta.5” . I am using webpacker. the format sent is HTML instead of turbo_stream. Any advices will be amazing
<h1>All Apps</h1>
<%= turbo_frame_tag "search" do %>
<%= form_with url: "/search", method: :get , data: { controller: "search" } do |form| %>
<%= form.text_field :search , data: { action: "input->search#findResults" } %>
<% end %>
<% end %>
<%= turbo_frame_tag "apps" do %>
<ul>
<% @apps.each do |app| %>
<%= content_tag :li, app.name %>
<% end %>
</ul>
<% end %>
How are you submitting the form? inside the stimulus controller?
I have faced similar issues on my search forms, i have fixed them by using this stimulus controller. after tinkering around and a-lot of useful comments on this site, i came up with this.
accept_turbo_stream_controller.js
import { Controller } from "stimulus";
export default class extends Controller {
connect() {
window.addEventListener(
"turbo:before-fetch-request",
this.appendTurboToHeaders
);
}
disconnect() {
window.removeEventListener(
"turbo:before-fetch-request",
this.appendTurboToHeaders
);
}
appendTurboToHeaders(event) {
let { headers } = event.detail.fetchOptions || {};
if (headers) {
headers.Accept = ["text/vnd.turbo-stream.html", headers.Accept].join(
", "
);
}
}
}
then inside your form do
<%= turbo_frame_tag "search" do %>
<%= form_with url: "/search", method: :get , data: { controller: "search accept-turbo-stream" } do |form| %>
<%= form.text_field :search , data: { action: "input->search#findResults" } %>
<% end %>
<% end %>