Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save danielabar/1c695aace8f8b20ccd358797f9b3d39f to your computer and use it in GitHub Desktop.
Save danielabar/1c695aace8f8b20ccd358797f9b3d39f to your computer and use it in GitHub Desktop.
Real time search with Hotwire
def search
@pagy, @bookmarks = if params[:search].present?
pagy(@bookmarks.search(params[:search]), params: ->(params) { params.merge!({search: params[:search]}) })
else
pagy(@bookmarks)
end
end
import { Controller } from "@hotwired/stimulus"
// Connects to data-controller="form-submit"
// Use data-action="input->form-submit#submit" to auto-submit a form on input
export default class extends Controller {
submit() {
clearTimeout(this.timeout)
this.timeout = setTimeout(() => {
this.element.requestSubmit();
}, 100)
}
}
<%= form_with(url: search_path, class: "flex-grow", data: { turbo_stream: true, controller: "form-submit" }) do |form| %>
<div class="flex items-center justify-center w-full">
<div class="relative flex items-center w-full flex-wrap">
<%= form.text_field :search, placeholder: "Search", class: "bg-white border-slate-400 rounded-full grow px-6 py-3 cursor-pointer", data: { action: "input->form-submit#submit" } %>
<span class="z-10 absolute items-center justify-center w-8 right-0 pr-3 py-3 cursor-pointer">
<i class="fa-solid fa-magnifying-glass text-slate-900"></i>
</span>
</div>
</div>
<% end %>
post "search", to: "bookmarks#search"
<%= turbo_stream.replace "bookmarks" do %>
<%= render "bookmarks/bookmarks", { bookmarks: @bookmarks, pagy: @pagy } %>
<% end %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment