Stimulus unmount action
a pattern to unmount action in Stimulus using a preventAction boolean state variable
by adrienpoly
HTML
<script src="https://unpkg.com/[email protected]/dist/stimulus.umd.js"></script>
<div data-controller="update">
<button data-action="update#fakeFetch">Fetch Data</button>
<button data-action="update#toggleFetchAction">Disable Fetch Action</button>
<ul data-target="update.results"></ul>
</div>
Babel + JSX
class UpdateController extends Stimulus.Controller {
static get targets() {
return ["results"];
}
initialize() {
this.preventFetch = false;
}
toggleFetchAction(e) {
this.preventFetch = !this.preventFetch;
e.target.textContent = this.preventFetch
? "Enable Fetch Action"
: "Disable Fetch Action";
}
fakeFetch() {
if (this.preventFetch) return;
const length = Math.ceil(Math.random() * 20) + 2;
this.resultsTarget.innerHTML = Array.from(
{ length },
() => `
<li data-action="click->autocomplete#redirect">
${Math.random()
.toString()
.slice(-10)}
</li>`
).join("");
}
set preventFetch(bool) {
this.data.set("prevent-fetch", bool);
}
get preventFetch() {
return this.data.get("prevent-fetch") === "true";
}
}
const application = Stimulus.Application.start();
application.register("update", UpdateController);