I have rails 7 app where I'm trying to build a search bar using either tom-select or slim-select. My issue reproduces no matter which library I'm using therefore it must be the issue on my rails side.
app/views/cities/index.html.erb
<%= form_for :city, url: cities_path, method: 'GET' do |f| %>
<div class="mt-4 border bg-light px-4 py-3 rounded-3">
<%= f.select :search_city, [], {},
placeholder: 'Type to search',
data: {
controller: 'ts--search',
ts__search_url_value: autocomplete_cities_path
} %>
<%= f.submit 'Search', class: 'btn mx-auto' %>
</div>
<% end %>
and this is my js controller (in this case I'm using tom-select) app/javascript/controllers/ts/search_controller.js
import { Controller } from "@hotwired/stimulus";
import { get } from "@rails/request.js";
import TomSelect from "tom-select";
export default class extends Controller {
static values = { url: String };
connect() {
var config = {
plugins: ["input_autogrow", "remove_button", "no_active_items"],
render: {
option: this.render_option,
item: this.render_option,
},
valueField: "value",
loadThrottle: 400,
load: (q, callback) => this.search(q, callback),
closeAfterSelect: true,
persist: false,
create: false,
delimiter: ", ",
maxItems: 10,
};
new TomSelect(this.element, config);
}
async search(q, callback) {
const response = await get(this.urlValue, {
query: { query: q },
responseKind: "json",
});
if (response.ok) {
callback(await response.json);
} else {
console.log("Error in search_ctrl: ");
callback();
}
}
render_option(data, escape) {
return `<div>${escape(data.text)}</div>`;
}
}
app/controllers/cities_controller.rb
class CitiesController < ApplicationController
def index
end
def autocomplete
list = City.order(:name)
.where("name ilike :q", q: "%#{params[:q]}%")
render json: list.map { |u| { text: u.name, value: u.id, sub: u.state } }
end
end
Problem Repro:
- Open cities index and click on the search bar.
- Dropdown opens up, I can type, and select a suggestion. Once selected, suggestion appears in the search bar with an 'x' clicking which will remove the it from the search bar.
- I add any amount of search tokens, 1-N.
- Click "Search" -> Seeing the results page.
- Click the back button in the browser (or swipe back on a phone)
Expected behavior: The search bar is exactly as it was before the search. clicking on 'x' removes the token. clicking on the Search bar allows entering the search query and adding more tokens.
Actual behavior: I can see the tokens, but clicking anything but the 'Search' button, does nothing. I can see the same behavior across multiple demos like this one and this one.
How can i make the JS work after coming back?