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
autocomplete
Stimulus controller, and make it listen to theinput
- When user type in the
input
element, theinput
event would fire, we send aGET
request to the server, and the server returnTurbo Stream
response 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.