0

I followed this tutorial to implement drag and drop. https://www.driftingruby.com/episodes/drag-and-drop-with-hotwire

I am getting an error on drop that says Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'dataset'). Any thoughts on why this is happening?

Project model:

acts_as_list scope: :project

_project.html.erb

<div id="projects" data-controller="position">
 <%= content_tag :div, data: { sgid: project.to_sgid_param, id: "#{dom_id project}" }, class: 'table-row' do %> <div><%= project.name %> </div>
   <div><%= project.description %> </div>
   <div><%= project.status %> </div>
   <div><%= project.user.email %> </div>
    <div class="flex justify-end">
     <%= link_to "View", project_path(project) , data: {turbo: false} %>
     <%= button_to "Delete", project, method: :delete, form: {data: {turbo_confirm: "Are you sure?"}} %> </div>
   </div>
<% end %>
</div>

position_controller.js

import { Controller } from "@hotwired/stimulus";
import Sortable from "sortablejs"
import { put, get, post, patch, destroy } from "@rails/request.js"

export default class extends Controller {

  connect() {
    this.sortable = Sortable.create(this.element, {
      animation: 150,
      onEnd: this.updatePosition.bind(this)
    })
  }

  async updatePosition(event) {
    const response = await put('/projects', {
      body: JSON.stringify({
        sgid: event.project.dataset.sgid,
        position: event.newIndex + 1
      })
    })
    if (response.ok) {
      console.log(event.project.dataset.sgid)
    }
  }
}
2
  • what element is the position_controller attached to? I don't see it in the markup. Maybe I missed it because of all the unnecessary styling classes you have included in the question! Pro-tip, you'll get better responses if you make the question easy to read without scrolling. Commented Sep 7, 2022 at 23:12
  • Thanks! I forgot to include the reference to the position controller. I updated the OP. It is in _project.html.erb.
    – spacerobot
    Commented Sep 8, 2022 at 4:05

1 Answer 1

0

well event doesn't have a method project. You may have meant event.target. Anyway it looks as if the target of the event is probably the #projects element (but you need to check this in dev tools and see where the event is being captured).

Let's suppose that the event is being captured by the #projects element, well that element has an empty dataList. So wherever the capture is occurring, you need to put data: {sgid: project.to_sgid_param} on that element.

Finally, you should be able to populate the ajax request with the value sgid: event.target.dataset.sgid.

1
  • Thanks for the suggestions. I had other problems with this method as well so I ended up doing something different that I got working!
    – spacerobot
    Commented Sep 9, 2022 at 10:44

Not the answer you're looking for? Browse other questions tagged or ask your own question.