Guys, I’m having great difficulty defining a property that is shared with methods using Hotwire’s Stimullus.
What happens is that I can’t keep the value of the this.draggedElement
property when I set a new value for it in the startDrag
method. When I use this property in the drop
method the new value I want to set disappears and returns null
, I’ve been stuck for a few days, I don’t know what else it could be.
I’ve tried using values as in Stimulus Reference but I’ve been unsuccessful.
import { Controller } from "@hotwired/stimulus";
export default class extends Controller {;
initialize(){
this.draggedElement = null
}
startDrag(event) {
this.draggedElement = event.currentTarget;
console.log("LOG Start DraggedElement", this.draggedElement)
}
dragOver(event) {
event.preventDefault();
}
drop(event) {
event.preventDefault();
console.log("LOG Drop DraggedElement", this.draggedElement)
if (deleteZone && this.draggedElement) {
const taskId = this.draggedElement.dataset.id;
fetch(`/tasks/${taskId}`, {
method: "DELETE",
headers: {
"X-CSRF-Token": document.querySelector("meta[name='csrf-token']").content
}
}).then(response => {
if (response.ok) {
this.draggedElement.remove();
}
});
this.draggedElement = null;
}
}
}
<div class="flex w-full h-screen bg-rose">
<%= render 'shared/aside' %>
<section class="w-full h-full bg-cream-white flex flex-col">
<div class="flex w-full items-center justify-between pt-16 pl-16">
<input type="text" name="" id="" placeholder="Search notes" class="w-5/6 h-12 border-none rounded-lg"/>
<button class="flex items-center justify-center w-10 h-10 rounded-full">
<%= image_tag 'icons/moon.svg'%>
</button>
</div>
<div class="w-full mt-12 pl-16">
<h2 class="text-3xl">Hello Fulano! 👋🏼</h2>
<p class="mt-2">All your notes are here, in one place!</p>
</div>
<div id="tasks" class="w-full h-full mt-12 flex flex-wrap gap-14 pl-16">
<%= render 'new_task'%>
<% @tasks.each do |task| %>
<%= render 'task', task: task %>
<% end %>
</div>
<section
data-task-target="deleteZone"
data-controller="task"
data-action="dragover->task#dragOver drop->task#drop"
class="w-full h-1/6 flex items-center justify-center">
<div class="w-3/5 h-full flex flex-col items-center justify-center gap-2">
<%= image_tag 'icons/trash.svg', class:'w-12' %>
<p class="text-red-500 text-sm">Drag to Delete Note</p>
</div>
</section>
</section>
</div>