Client Side and Server Side Sorting in Lightning Data Table LWC | LWC Stack ☁️⚡️


 In this video I will show you how you can add sorting to a Lightning Data Table in Lightning Web Component.

We will be having two examples today :-

1. Client Side Sorting (Sorting the cached data)

2. Server Side Sorting (Sorting using apex callout)


Client Side Sorting

In client side sorting we will apply sorting to local cached data, so it will be little faster as compare to Server side sorting.

You should only use it when you have to play with a limited set of records. For example maybe you need a datatable component on dashboard where you will display recent records only.

To apply the sorting you have to keep sortable attribute to true in lightning data table columns. And in datatable you can use sorted-by attribute to store field name, sorted-direction attribute to store the direction (asc/desc) and the onsort function to sort the data.

Please check below example

HTML

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
<template>
  <lightning-card title="Sorting Client Side" icon-name="custom:custom63">
    <div class="slds-m-around_medium">
      <template if:true={contacts}>
        <lightning-datatable
          key-field="Id"
          data={contacts}
          columns={columns}
          sorted-by={sortedBy}
          sorted-direction={sortedDirection}
          onsort={onSort}
        >
        </lightning-datatable>
      </template>
      <template if:true={error}>
        <!-- handle Apex error -->
      </template>
    </div>
  </lightning-card>
</template>


JS

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import { LightningElement, wire, track } from "lwc";
import getAllContacts from "@salesforce/apex/ContactController.getAllContacts";

const COLS = [
  {
    label: "First Name",
    fieldName: "FirstName",
    editable: true,
    sortable: "true"
  },
  {
    label: "Last Name",
    fieldName: "LastName",
    editable: true,
    sortable: "true"
  },
  { label: "Phone", fieldName: "Phone", type: "phone", sortable: "true" },
  { label: "Email", fieldName: "Email", type: "email", sortable: "true" }
];
export default class Sorting extends LightningElement {
  @track columns = COLS;
  @track contacts;
  @track sortedBy;
  @track sortedDirection;

  @wire(getAllContacts)
  wiredContacts(result) {
    if (result.data) {
      this.contacts = result.data;
      this.error = undefined;
    } else if (result.error) {
      this.error = result.error;
      this.data = undefined;
      console.log("###Error : " + JSON.stringify(this.error));
    }
  }
  onSort(event) {
    this.sortedBy = event.detail.fieldName;
    this.sortedDirection = event.detail.sortDirection;
    this.sortData(this.sortedBy, this.sortedDirection);
  }

  sortData(fieldname, direction) {
    let parseData = JSON.parse(JSON.stringify(this.contacts));
    let keyValue = (a) => {
      return a[fieldname];
    };
    let isReverse = direction === "asc" ? 1 : -1;
    parseData.sort((x, y) => {
      x = keyValue(x) ? keyValue(x) : "";
      y = keyValue(y) ? keyValue(y) : "";
      return isReverse * ((x > y) - (y > x));
    });
    this.contacts = parseData;
  }
}


APEX

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
public with sharing class ContactController {
    @AuraEnabled(cacheable=true)
    public static List<Contact> getAllContacts() {
        return [
            SELECT Id, FirstName, LastName, Title, Phone, Email
            FROM Contact
            WITH SECURITY_ENFORCED
            limit 10
        ];
    }
}


Server Side Sorting

You may use server side sorting when you have to deal with large amount of data. We will be using pretty much similar functionality in it. The difference will be just in SOQL where we will be passing the field namd and direction of sorting.

Please check example below : 

HTML

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
<template>
  <lightning-card title="Sorting Server Side" icon-name="custom:custom63">
    <div class="slds-m-around_medium">
      <template if:true={contacts}>
        <lightning-datatable
          key-field="Id"
          data={contacts}
          columns={columns}
          sorted-by={sortedBy}
          sorted-direction={sortedDirection}
          onsort={onSort}
        >
        </lightning-datatable>
      </template>
      <template if:true={error}>
        <!-- handle Apex error -->
      </template>
    </div>
  </lightning-card>
</template>


JS

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import { LightningElement, wire, track } from "lwc";
import getAllContacts from "@salesforce/apex/ContactController.getAllContactsSorting";

const COLS = [
  {
    label: "First Name",
    fieldName: "FirstName",
    editable: true,
    sortable: "true"
  },
  {
    label: "Last Name",
    fieldName: "LastName",
    editable: true,
    sortable: "true"
  },
  { label: "Phone", fieldName: "Phone", type: "phone", sortable: "true" },
  { label: "Email", fieldName: "Email", type: "email", sortable: "true" }
];
export default class SortingServerSide extends LightningElement {
  @track columns = COLS;
  @track contacts;
  @track sortedBy = "FirstName";
  @track sortedDirection = "asc";

  @wire(getAllContacts, { orderBy: "$sortedBy", direction: "$sortedDirection" })
  wiredContacts(result) {
    if (result.data) {
      this.contacts = result.data;
      this.error = undefined;
    } else if (result.error) {
      this.error = result.error;
      this.data = undefined;
      console.log("###Error : " + JSON.stringify(this.error));
    }
  }
  onSort(event) {
    this.sortedBy = event.detail.fieldName;
    this.sortedDirection = event.detail.sortDirection;
  }
}


APEX

1
2
3
4
5
6
7
8
9
public with sharing class ContactController {
    @AuraEnabled(Cacheable=true)
    public static List <Contact> getAllContactsSorting(String orderBy, String direction) {
        String query;
        query  = 'SELECT Id, FirstName, LastName, Phone, Email FROM Contact';
            query += ' ORDER BY '+orderBy+' '+direction;
        return Database.query(query);
    }
}


Output



Checkout complete video tutorial below

 If you have any question please leave a comment below.

If you would like to add something to this post please leave a comment below.
Share this blog with your friends if you find it helpful somehow !

Thanks
Happy Coding :)

Post a Comment

0 Comments