1

I am having trouble refreshing a Datatable in my Lightning Web Component after updating a record. I am calling an onclick action on a button within the row, and imperatively calling an Apex method to update that record. I then call the refreshApex() to update the data being fed into the Datatable.

However, after the refreshApex(), the tables within the for:each are not being refreshed with new data.

The records are properly modified and reflect the changes properly when refreshing the entire page.

Note: The Task object is not supported in LWC, and I cannot use the updateRecord() method to update these records.

HTML:

<template>
  <template if:true="{taskCompWrapperList}">
    <!--<lightning-layout multiple-rows="false" pull-to-boundary="small">-->
    <template for:each="{taskCompWrapperList}" for:item="taskTemplate">
      <lightning-layout-item
        key="{taskTemplate.taskSectionOrder}"
        size="3"
        class="slds-p-around_x-small"
      >
        <!-- Start bear tile -->
        <lightning-card title="{taskTemplate.taskSectionTitle}">
          <div class="slds-m-around_medium">
            <template if:true="{taskTemplate.taskList}">
              <lightning-datatable
                key-field="Id"
                data="{taskTemplate.taskList}"
                onrowaction="{handleRowAction}"
                columns="{columns}"
                onsave="{handleSave}"
                draft-values="{draftValues}"
              >
              </lightning-datatable>
            </template>
            <template if:true="{contact.error}">
              <!-- handle Apex error -->
            </template>
          </div>
        </lightning-card>
        <!-- End bear tile -->
      </lightning-layout-item>
    </template>
    <!--</lightning-layout>-->
  </template>
</template>

Javascript:

import { LightningElement, api, wire ,track} from 'lwc';
import getTaskCompWrappers from '@salesforce/apex/ENT_Task_Utility.getTaskComponentWrapper';
import updateTask from '@salesforce/apex/ENT_Task_Utility.updateTask';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { updateRecord } from 'lightning/uiRecordApi';
import { refreshApex } from '@salesforce/apex';

const COLS = [
    {        
        type: 'button',
        label: 'Complete',
        typeAttributes: 
        {
            //iconName: 'action:preview',
            label: 'Complete',
            name: 'Complete',
            title: 'Complete',
            value: 'Complete',
            variant: 'brand',
            alternativeText: 'Complete'
        }
    },
    {        
        type: 'button-icon', 
        label: 'Start',       
        typeAttributes: 
        {
            iconName: 'action:approval',
            //label: 'Complete',
            name: 'Start',
            title: 'Start',
            value: 'Start',
            variant: 'success',            
            alternativeText: 'Start',
        }
    },
    {
        type: "button", 
        typeAttributes: 
        {  
            label: 'View',  
            name: 'View',  
            title: 'View',  
            disabled: false,  
            value: 'view',  
            iconPosition: 'left'  
        }
    },  
    {
        type: "button", 
        typeAttributes: 
        {  
            label: 'Edit',  
            name: 'Edit',  
            title: 'Edit',  
            disabled: false,  
            value: 'edit',  
            iconPosition: 'left'  
        }
    },  
    //{ label: 'Complete', fieldName: 'Task_Complete__c', editable: true },
    { label: 'Status', fieldName: 'Status', type: 'picklist', editable: true },
    { label: 'Completed', fieldName: 'Completed', type: 'boolean', editable: true },
    { label: 'Owner', fieldName: 'OwnerId', editable: true },
    { label: 'Subject', fieldName: 'Subject' },
    { label: 'Due Date', fieldName: 'ActivityDate', type: 'date' }
];

export default class ENT_Task_Utility_LWC extends LightningElement {
    @api objApiName;
    @api recordId;
    @track testMessage = 'Test Failed :c';  

    @track error;
    @track columns = COLS;
    @track draftValues = [];
    taskCompWrapperList;
    @track error;

    //@wire(getTasks, {recordId: '$recordId'}) taskList;`
    @wire(getTaskCompWrappers, {recordId: '$recordId', objApiName: '$objApiName'}) 
    taskCompWrapperListWire({ error, data }) {
        if (data) {
            this.taskCompWrapperList = data;
            this.error = undefined;
        } else if (error) {
            this.error = error;
            this.taskCompWrapperList = undefined;
        }
    }

    updateTaskValues (taskId, taskStatus) {
        // eslint-disable-next-line no-console
        console.log('updateTaskValues hit');
        for(var counter = 0; counter < this.taskCompWrapperList.length; counter++) {
            // eslint-disable-next-line no-console
            console.log('taskWrapper: ' + this.taskCompWrapperList[counter]);
            for(var counter2 = 0; counter2 < this.taskCompWrapperList[counter].taskList.length; counter2++) {
                // eslint-disable-next-line no-console
                console.log('task: ' + this.taskCompWrapperList[counter].taskList[counter2]);
                if(this.taskCompWrapperList[counter].taskList[counter2].Id == taskId)
                {
                    this.dispatchEvent(
                        new ShowToastEvent({
                            title: 'Task Id Found!',
                            message: this.taskCompWrapperList[counter].taskList[counter2].Id,
                            variant: 'success'
                        })
                    );
                    this.taskCompWrapperList[counter].taskList[counter2].Status = taskStatus;
                }
            }
        }
    }

    handleRowAction(event) {
        //TODO
    }    
}

Apex methods:

@AuraEnabled(cacheable=true)
    global static List<Task> getTasks(String recordId)
    {
        return [SELECT Id, Subject, OwnerId FROM Task WHERE WhatId = :recordId];
    }

    @AuraEnabled(cacheable=true)
    global static List<ENT_Task_Comp_Wrapper> getTaskComponentWrapper(String recordId, String objApiName)
    {
        List<Task_Template__c> taskTemplateList = [SELECT Id, Task_Component_Section_Order__c, Task_Component_Section_Title__c, (SELECT Id FROM Task_Template_Items__r) 
                                                   FROM Task_Template__c 
                                                   WHERE Active__c = true AND sObject__c = :objApiName ORDER BY Task_Component_Section_Order__c ASC];

        List<Task> taskList = [SELECT Id, Task_Template_Item__c, OwnerId, Owner.Name, Subject, Description, Status, ActivityDate, Task_Complete__c FROM TasK WHERE WhatId = :recordId];

        List<ENT_Task_Comp_Wrapper> taskCompWrapperList = new List<ENT_Task_Comp_Wrapper>();

        for(Task_Template__c taskTemplate : taskTemplateList)
        {
            ENT_Task_Comp_Wrapper taskCompWrapper = new ENT_Task_Comp_Wrapper();
            taskCompWrapper.taskSectionTitle = taskTemplate.Task_Component_Section_Title__c;
            taskCompWrapper.taskSectionOrder = (Integer)taskTemplate.Task_Component_Section_Order__c;
            taskCompWrapper.taskList = new List<Task>();

            for(Task currentTask : taskList)
            {
                for(Task_Template_Item__c taskTemplateItem : taskTemplate.Task_Template_Items__r)
                {
                    if(taskTemplateItem.Id == currentTask.Task_Template_Item__c)
                    {
                        taskCompWrapper.taskList.add(currentTask);
                    }
                }
            }

            taskCompWrapperList.add(taskCompWrapper);

        }
        System.debug(taskCompWrapperList);
        return taskCompWrapperList;
    }

    @AuraEnabled
    global static void updateTask(String taskId, String newStatus)
    {
        System.debug(taskId);
        Task taskToUpdate = new Task(Id = taskId, Status = newStatus);
        update taskToUpdate;
        //update taskToUpdate;
    }

@AuraEnabled
    global static void updateTask(String taskId, String newStatus)
    {
        System.debug(taskId);
        Task taskToUpdate = new Task(Id = taskId, Status = newStatus);
        update taskToUpdate;
        //update taskToUpdate;
    }
keikai
  • 14,085
  • 9
  • 49
  • 68
rvmorada
  • 11
  • 1
  • 2

3 Answers3

0

In your JS code you have imported refreshApex by using this line import { refreshApex } from '@salesforce/apex';

but you didn't assigned to any wire method. Hence data is not refreshed

Please refer this documentation.

To refresh a wired method, pass the argument the wired method receives (which is the wired value) to refreshApex(). In this sample code, the wired method is taskCompWrapperListWire. Hold on to the value provisioned by the wire service and pass it to refreshApex().

@wire(getTaskCompWrappers, {recordId: '$recordId', objApiName: '$objApiName'}) 
taskCompWrapperListWire({ error, data }) {
    if (data) {
        this.taskCompWrapperList = data;
        this.error = undefined;
    } else if (error) {
        this.error = error;
        this.taskCompWrapperList = undefined;
    }
}

And then use refreshApex() as below:

refreshApex(this.taskCompWrapperListWire);

Update you code as below

updateTaskValues({
        taskId: this.taskId,
        taskStatus: this. taskStatus
   })
    .then(() => {
        // your code logic 
        refreshApex(this.taskCompWrapperListWire);
    })
    .catch((error) => {
        this.message = 'Error received: code' + error.errorCode + ', ' +
            'message ' + error.body.message;
    });
Sudarshan
  • 363
  • 1
  • 9
0

you probably need to wait for next release to have a correct way to handle such situation.

You are getting record through uiRecordApi and updating through Apex if I'm correct. Then you would need to use getRecordNotifyChange() available in Winter 21 release.

Bartheleway
  • 528
  • 5
  • 19
0

Apart from the answer provided by Sudarshan, you should also define taskCompWrapperList as a reactive property to make it rerender when the property is updated.

@track taskCompWrapperList = [];
Shreemaan Abhishek
  • 1,134
  • 1
  • 7
  • 33