Cannot read properties of undefined (reading 'element') when accessing event object

Viewed 1045

So I am using Vue Draggable and I am to access the event object in VueJs like below:

<draggable group="leads"
   :list="newLeads"
   @change="seeChange($event, 'New')">

In methods:

async seeChange(event, status) {

    console.log(event.added.element.id);

 await axios.patch('http://localhost/api/leads/'+event.added.element.id+'/update-status', 
{status : status}).then(response => {

        this.leads.unshift(response.data.data);
        
        this.getLeads();
    }).catch(error => {
      console.log(error);
    });

  },

I can see the id in the console. But when I drag the card (triggering the event) I get a

Cannot read properties of undefined (reading 'element')

error when the card lands. Even the Axios call gets the correct id and the request is sent fine. But the white screen with this error appears nonetheless.

What am I missing?

2 Answers

Change event is called with one argument containing one of the following properties: added, removed, moved. Docs.

event.added contains information of an element added to the array but when you do removed, moved you haven't property added in object event.

You can use it like this:

async seeChange(event, status) {
    console.log(event?.added.element.id);

    if(event.added) {
           await axios.patch('http://localhost/api/leads/'+event.added.element.id+'/update-status', {status : status}).then(response => {
              this.leads.unshift(response.data.data);
              this.getLeads();
           }).catch(error => {
              console.log(error);
           });
    }
}

request will be send only after added event.

If you want to send request on each event you can do it by using Object.values(event)[0], example:

async seeChange(event, status) {
    const id = Object.values(event)[0].element.id;
    console.log(id);

           await axios.patch('http://localhost/api/leads/'+id+'/update-status', {status : status}).then(response => {
              this.leads.unshift(response.data.data);
              this.getLeads();
           }).catch(error => {
              console.log(error);
           });
    
}
Related