0

I have an array I use for a paginated list in a dynamic table inside a lightning web component. I'm trying to get the sort function working to adjust the data based on which column is clicked, but I'm getting an interesting error message. Whenever I click the column I get: [Cannot assign to read only property '0' of object '[object Array]'].

Now, I know that data returned from the server is static, so a copy needs to be used to prevent a cache error, but I'm apparently still going wrong some place. If someone could take a look at the method and give any guidance it'd be appreciated. This is the method, wherein this.objectList is my copy of the data returned from the server in a previous call:

sort(event){
    console.log('Sort Event Caused by: ' + event.target.value);
    var field = event.target.value;
    var pageSize = this.pageSize;   
    var sortAsc = this.sortAsc;
    let records = this.objectLst;
    var paginationList = [];
    var i;
    const key = (a) => {
        let fieldValue = a[field] ? (typeof a[field] === 'string' ? a[field].toLowerCase() : a[field]) : '';
       return fieldValue; 
        }
    let reverse = sortAsc === 'asc' ? 1: -1;

        this.sortAsc = sortAsc;
        this.sortField = field;
        this.objectList = records.sort((a,b) => {
            return reverse * ((key(a) > key(b)) - (key(b) > key(a)));
        });

        this.start = 0;
        this.end = pageSize-1;
        if(this.end >= this.totalSize){
            this.nextButtonDisabled = true;
            }
        else{
            this.nextButtonDisabled = false;
           }

        if(this.start === 0){
            this.prevButtonDisabled = true;
            }
        else{
            this.prevButtonDisabled = false;
           }
        for(i=0; i< pageSize; i++){
            paginationList.push(records[i]);
            }
        this.paginationList = paginationList;
    }

1 Answer 1

1

Assigning a variable to another variable doesn't make a copy. You need to actually copy it:

let records = [...this.objectList];

Array.prototype.sort sorts the current Array; it does not copy the array before sorting.

1
  • Yes, that was my error, thanks for the correction. Jan 23, 2020 at 12:36

You must log in to answer this question.

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