I have multiple data tables that I am trying to sort columns on separately. When I click on the column of one table to sort it, the same column on all data tables is being sorted as well.
Update: Using separate data sets on each table, but now I get an error when clicking to sort any column:
None of the columns sort when clicked, but the arrow indicating the sort direction does change.
datatable.html
<template>
<lightning-card title="Tables">
<p>Table 1</p>
<lightning-datatable
key-field="id"
data={dataOne}
columns={nameColumns}
sorted-by={sortByDataOne}
sorted-direction={sortDirectionDataOne}
onsort={handleSortDataOne}>
</lightning-datatable>
<p>Table 2</p>
<lightning-datatable
key-field="id"
data={dataTwo}
columns={nameColumns}
sorted-by={sortByDataTwo}
sorted-direction={sortDirectionDataTwo}
onsort={handleSortDataTwo}>
</lightning-datatable>
</lightning-card>
</template>
datatable.js
import { LightningElement, track } from 'lwc';
const nameColumns = [
{ label: 'First Name', fieldName: 'firstName', sortable: 'true'},
{ label: 'Last Name', fieldName: 'lastName', sortable: 'true'},
];
const dataOne = [
{ firstName: 'John', lastName: 'Doe'},
{ firstName: 'Carl', lastName: 'Smith'}
];
const dataTwo = [
{ firstName: 'John', lastName: 'Doe'},
{ firstName: 'Carl', lastName: 'Smith'}
];
export default class Datatable extends LightningElement {
@track sortByDataOne;
@track sortByDataTwo;
@track sortDirectionDataOne;
@track sortDirectionDataTwo;
@track nameColumns = nameColumns;
@track dataOne = dataOne;
@track dataTwo = dataTwo;
handleSortDataOne(event) {
this.sortByDataOne = event.detail.fieldName;
this.sortDirectionDataOne = event.detail.sortDirectionDataOne;
this.sortDataOne(event.detail.fieldName, event.detail.sortDirectionDataOne);
};
sortDataOne() {
let fieldName = this.sortByDataOne;
let sortDirectionDataOne = this.sortDirectionDataOne;
let parseData = JSON.parse(JSON.stringify(this.dataOne));
let keyValue = (a) => {
return a[fieldName];
};
let isReverse = sortDirectionDataOne === 'asc' ? 1: -1;
parseData.sort((x, y) => {
x = keyValue(x) ? keyValue(x) : '';
y = keyValue(y) ? keyValue(y) : '';
return isReverse * ((x > y) - (y > x));
});
this.dataOne = parseData;
};
handleSortDataTwo(event) {
this.sortByDataTwo = event.detail.fieldName;
this.sortDirectionDataTwo = event.detail.sortDirectionDataTwo;
this.sortDataTwo(event.detail.fieldName, event.detail.sortDirectionDataTwo);
};
sortDataTwo() {
let fieldName = this.sortByDataTwo;
let sortDirectionDataTwo = this.sortDirectionDataTwo;
let parseData = JSON.parse(JSON.stringify(this.dataTwo));
let keyValue = (a) => {
return a[fieldName];
};
let isReverse = sortDirectionDataTwo === 'asc' ? 1: -1;
parseData.sort((x, y) => {
x = keyValue(x) ? keyValue(x) : '';
y = keyValue(y) ? keyValue(y) : '';
return isReverse * ((x > y) - (y > x));
});
this.dataTwo = parseData;
};
}