1

I am not able to retrieve the correct line of the datatable on my LWC. Ive followed several searches but apparently Im still missing something.

Here is the HTML:

<lightning-datatable
                    key-field="id"
                    data={usersData}
                    columns={usersColumns}
                    onrowaction={handleRowAction}
                    show-row-number-column
                    hide-checkbox-column="true">
            </lightning-datatable>

here is the JS declaration and code:

const actions = [
    { label: 'Delete', name: 'delete' },
];

const columns = [
    { label: 'Name', fieldName: 'Name' },
    { label: 'Access Level', fieldName: 'AccessLevel' },
    {
        type: 'action',
        typeAttributes: { rowActions: actions },
    }
    
];

....

handleRowAction(event) {
        let actionName = event.detail.action.name;
        let row = event.detail.row;
        switch (actionName) {
            case 'delete':
                this.deleteRow(row);
                break;
            default:
        }


      }

deleteRow(row) {
        const { id } = row;
        const index = this.findRowIndexById(id);
        console.log(index);                
    }

findRowIndexById(id) {
        let ret = -1;
        this.usersData.some((row, index) => {
            if (row.id === id) {
                ret = index;
                return true;
            }
            return false;
        });
        return ret;
    }

It is always printing 0, even if I select the second or third lines.

1 Answer 1

1

There's a function that does what you're trying to do in findRowIndexById; it's Array.prototype.findIndex:

deleteRow(row) {
    const index = this.usersData.findIndex(user => user.id === row.id);
    console.log(index);                
}

Make sure that id is correct, and that is not, for example, Id. JavaScript is cAsE-sEnSiTiVe, so if you're referencing the wrong-cased field, this would be a symptom of why 0 is always returned, as you'd find undefined === undefined on the first index.

1
  • perfect answer my friend. I was retrieving the item as Id instead of id. That answer is exactly what was happening Commented May 3, 2021 at 12:05

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .