Type as Search
How it Works
<form action="{% url 'turbo-stream:task-list' %}"
method="get"
data-controller="autocomplete"
data-turbo-stream
>
<input type="text" placeholder="Search" name="title" data-autocomplete-target="input" />
</form>
Notes:
- We build a
autocompleteStimulus controller, and make it listen to theinput - When user type in the
inputelement, theinputevent would fire, we send aGETrequest to the server, and the server returnTurbo Streamresponse to update list and pagination.
import { Controller } from '@hotwired/stimulus';
import { debounce } from "../helpers";
export default class extends Controller {
static targets = ["input"];
connect() {
if (this.hasInputTarget) {
this.inputTarget.addEventListener("input", this.onInputChange);
}
}
disconnect() {
if (this.hasInputTarget) {
this.inputTarget.removeEventListener("input", this.onInputChange);
}
}
onInputChange = debounce(() => {
this.loadResults();
}, 500);
loadResults() {
this.element.requestSubmit();
}
}
Demo
https://hotwire-django.fly.dev/turbo-stream/
Try to input some text in the search box and the list would be updated automatically.