0

Im having this problem where the data not rerender even with @wire and @track to the variables. I checked on Chrome debug and see my asc/desc toggled but the data still not change. when i manually change the sortedDirection from asc and desc and commit, i can see the data rearrange. Please help me check if I make any mistake.

JS

 @api hideCheckboxColumn;
 @track sortedBy ='Stage__c' ;
 @track sortedDirection = 'asc' ;



/** Wired Apex result so it can be refreshed programmatically */
@track wiredResult;


@wire(getProjectsList, { assetId: '$propertyId', userId: '$userId', status: '$_status', hasProjectMembership: '$projectMemberOnly', page: '$currentpage', pageSize: '$pagesize', direction: '$sortedDirection',selectedField: '$sortedBy'}) 

wiredData(result) {

    this.wiredResult = result;
    if (result.data) {

        if (this._isSearchChangeExecuted && this._localCurrentPage === this.currentpage) {
            return;
        }
        this._isSearchChangeExecuted = true;
        this._localCurrentPage = this.currentpage;

        this.data = this.flattenData(result.data);
        this.error = undefined;
        this._projectCount = result.data.length;
        this.loaded = true;

        this.getRecordCount();

    } else if (result.error) {
        this.error = result.error;
        this.data = undefined;
        this.loaded = true;
    }
    else {
        this.loaded = true;
        this.data = undefined;
        this.error = undefined;
        this.totalrecords = 0;
        this.totalpages = 0;
    }

}
onClickColumnToSort(event){
    let fieldName = event.detail.fieldName;
    let sortDirection = event.detail.sortDirection;
    this.sortedBy = fieldName;
    this.sortedDirection = sortDirection;
    window.console.log(`Field : ${this.sortedBy} Direction : ${this.sortedDirection}`);
    //this.wiredResult.data = this.sortData(fieldName, sortDirection);
    window.console.log(`Field : ${this.data} Direction : ${this.wiredResult}`);
    //this.wiredResult.data =JSON.parse(JSON.stringify(this.wiredResult.data));

}
//for sorting



// for pagination
// get total record count
getRecordCount() {
    getRecordCount({ assetId: this.propertyId, status: this._status, hasProjectMembership: this.projectMemberOnly, direction: this.sortedDirection, selectedField: this.sortedBy })
        .then(count => {
            if (count !== 0 && count !== undefined) {
                this.totalrecords = count;
                this.totalpages = Math.ceil(this.totalrecords / this.pagesize);
            }
            else {
                this.totalpages = 1;
                this.totalrecords = 0;
            }

            const event = new CustomEvent('recordsloaded', {
                detail: { count: this.totalrecords, tab: 'projects', page: this._localCurrentPage }
            });
            this.dispatchEvent(event);
        })
        .catch(error => {
            this.error = error;
        });

}
@api 
    refreshData() {
        return refreshApex(this.wiredResult);
    }

HTML

<lightning-datatable class="slds-scrollable_none slds-table_striped" 
                    key-field="id" 
                    data={data} 
                    columns={columns} 
                    onrowaction={handleRowAction}
                    onsort={onClickColumnToSort}
                    sorted-by={sortedBy}
                    sorted-direction={sortedDirection}

                    hide-checkbox-column

                     > 
                </lightning-datatable>

APEX Controller

@AuraEnabled(cacheable=true)
public static List<RDC_Project__c> getProjectsList(String assetId, Id userId, String status, Boolean hasProjectMembership, Integer page, Integer pageSize, String direction, String selectedField)
{
    List<RDC_Project__c> result = new List<RDC_Project__c>();
    string query;
    Integer rowOffset = 0;
    Integer rowLimit = 1000;


    if (pageSize != 0) { rowLimit = pageSize; }
    if (rowLimit > 0 && page > 0) { rowOffset = (page - 1) * rowLimit; }

    string queryFields = 'SELECT id, name, cru__c, business_unit__c, business_unit__r.bldg_no__c, business_unit__r.asset_id__c, Business_Unit__r.name, ' +
                    'Tenant_Name__c, Tenant_Name__r.Name, unit__c, area__c, stage__c, Opportunity__c, Opportunity__r.Id, Opportunity__r.Name, Opportunity__r.StageName, ' +
                    'Percentage_Complete_Landlord__c, Percentage_Complete_Drawings__c, Percentage_Complete_Tenant__c, Project_Percentage_Complete__c ' +
                                       'FROM rdc_project__c ';

    string queryStage = 'WHERE stage__c != \'Complete\' ';


    if (status != null && status != '')
    {
        // any open stage (ie. not complete)
        if (status.toLowerCase() == 'open') { queryStage = 'WHERE stage__c != \'Complete\' '; }
        // closed stage only
        else if (status.toLowerCase() == 'closed') { queryStage = 'WHERE stage__c = \'Complete\' '; }
        // all stages
        else { queryStage = 'WHERE stage__c NOT IN (\'\') '; }
    }


    query = queryFields + queryStage;
    if (assetId != null && assetId != '')
    {
        // get projects for given asset ID
        query += 'AND business_unit__r.asset_id__c =: assetId ';
    }

    query+=' ORDER BY '+selectedField+' '+direction;
    //query += ' ORDER BY business_unit__r.name, cru__c ';

    // if (direction == 'asc'){
    //     query += ' ORDER BY '+selectedField+' '+direction;
    //     //'SELECT Id, FirstName, LastName FROM Contact ORDER BY '+selectedField+' '+direction
    //     //query += ' ORDER BY Stage__c ASC ';
    // } 
    // else if (direction == 'desc'){
    //     query += 'ORDER BY '+selectedField+' '+direction;
        //query += ' ORDER BY Stage__c DESC ';
    //}
    // else{
    //     query += ' ORDER BY Stage__c, cru__c ';
    // }
    //query += ' ORDER BY business_unit__r.name, cru__c ';

   //*** below for testing only ***/
   //query = [SELECT id, name, business_unit__r.bldg_no__c, business_unit__r.asset_id__c, Business_Unit__r.name,
   //                      Tenant_Name__r.Name, unit__c, area__c, stage__c, Opportunity__r.Id, Opportunity__r.Name
   //                                     FROM rdc_project__c 
    //                                    where stage__c not in ('')
     //                                   ORDER BY business_unit__r.name]

   if (hasProjectMembership) {
        return getProjectsByMembershipList(query, assetId, userId);
    }


    // if page==0 && pageSize==0, get everything (for full record count)
    if (page != 0 && pageSize != 0) {
        query += ' LIMIT :rowLimit OFFSET :rowOffset';
    }


    System.debug('THIS IS IT '+ query);
    result = Database.query(query);

    return result;

}

@AuraEnabled(cacheable=true)
public static Integer getRecordCount(String assetId, Id userId, String status, Boolean hasProjectMembership, String direction, String selectedField) {
    List<RDC_Project__c> lst = getProjectsList(assetId, userId, status, hasProjectMembership, 0, 0,direction,selectedField);
    return lst.size();
}
0

as far as i am concerned, the @track property rerenders when the value changes, in your case, data is an array, so if you sort it or add some elements using array.push() for example, the var value itself does not change as it is a reference.

Try sorting your array and then using this statement:

this.data = JSON.parse(JSON.stringify(this.data));

This way you make an exact copy of that array, changing the reference of the var data, making the @track property rerender the lightning-data-table.

I hope this helps you

1
  • Hi , if possible, could you please help me put in a example, like where will I put that line of code? Thanks
    – An Le
    Jan 14 '20 at 15:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.