function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Nitesh Jain 35Nitesh Jain 35 

Lightning data table does not re-render in LWC

Hello All,

Need your help in acheiving one requirement. I have list of accounts on one components, once we click on the Account, It fires an event ( Passing an AccountId). The event is received by some other components (No Parent-Child Relationship), the JS Connectec call back methods, Registers an event and then through wire method(Passing an AccountId received by Event), fethcing all the contacts, These contacts are then renders through Lightning data table ( Till this time, everything works as expected).
The problem occurs when i tries to add the empty row in Lightning data table, I can see in logs that List is being added but it does not re render the lightning data table and blank row is not added)
Best Answer chosen by Nitesh Jain 35
Nitesh Jain 35Nitesh Jain 35
hi Ugur, No success.
However it seems like the its always going to add the empty row at top Account and not getting the conext of current event .... For an example 
When I click the account 'AA-Nitesh Account Test 2'- It renders the contact list correct but when click on 'Add Row' it seems it always getting added to account 'AAAAA 1111 2' 
Examples....

All Answers

Nitesh Jain 35Nitesh Jain 35
HTML:
<template>

    <lightning-layout vertical-align="center">
        <lightning-layout-item padding="around-small">
            <template if:true={account}>
        <p>{account}</p>
        <p><template if:true={contactList.data}>{accountName}</template></p>
    </template>
</lightning-layout-item>

<lightning-layout-item padding="around-small" >
    <template if:true={contacts}>
     <!--   <template for:each={contactList.data} for:item="contact">
       <li key={contact.id}>{contact.FirstName}</li>
       <li key={contact.id}>{contact.LastName}</li>
        </template> -->
        <lightning-datatable
                    key-field="Id"
                    data={contacts}
                    columns={columns}
                    onsave={handleSave}
                    draft-values={draftValues}>
                </lightning-datatable>
              
                
 <lightning-button variant="brand" label="Add Row" title="Add Row" onclick={handleClick} > </lightning-button>          
    </template>
    <template if:true={error}>
        <p> {error}></p>
    </template>

</lightning-layout-item>

</lightning-layout>
    
</template>


JS:

import { LightningElement,api,wire,track } from 'lwc';
import getContacts from '@salesforce/apex/ContactData.getContacts';
import pubsub from 'c/pubsub' ; 
import { updateRecord } from 'lightning/uiRecordApi';
import { refreshApex } from '@salesforce/apex';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import FIRSTNAME_FIELD from '@salesforce/schema/Contact.FirstName';
import LASTNAME_FIELD from '@salesforce/schema/Contact.LastName';
import ID_FIELD from '@salesforce/schema/Contact.Id';

/* eslint-disable no-console */
 /* eslint-disable no-alert */

 const COLS = [
    { label: 'First Name', fieldName: 'FirstName', editable: true },
    { label: 'Last Name', fieldName: 'LastName', editable: true },
    { label: 'Title', fieldName: 'Title', editable: true },
    { label: 'Phone', fieldName: 'Phone', type: 'phone' },
    { label: 'Email', fieldName: 'Email', type: 'email' }];

export default class DisplayContact extends LightningElement {
    @api account;
    @track Contacts;
    @track error;
     @track accountName=null;
    @track columns = COLS;
    @track draftValues = [];
    
    handleSave(event) {
              const fields = {};
        fields[ID_FIELD.fieldApiName] = event.detail.draftValues[0].Id;
        fields[FIRSTNAME_FIELD.fieldApiName] = event.detail.draftValues[0].FirstName;
        fields[LASTNAME_FIELD.fieldApiName] = event.detail.draftValues[0].LastName;
        const recordInput = {fields};

        updateRecord(recordInput)
        .then(() => {
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Success',
                    message: 'Contact updated',
                    variant: 'success'
                })
            );
            // Clear all draft values
            this.draftValues = [];

            // Display fresh data in the datatable
            return refreshApex(this.contactList);
        }).catch(error => {
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Error creating record',
                    message: error.body.message,
                    variant: 'error'
                })
            );
        });
    }

    eventFiredCallback;
    eventFired(event){ 
        this.account=event  ;  
    console.log('This is new Log for Acc',this.account,this.accountName);
        //this.refresh();
    }
    connectedCallback(){
       // this.data='callback' ; 
       //this.accountName=this.contactList.data ? this.contactList.data[0].Account.Name :null;

        this.eventFiredCallback = this.eventFired.bind(this); 
        this.register();
    }

    @api
    register(){
       // this.data+=' - register' ;
        pubsub.register('selected', this.eventFiredCallback ); 
    } 

    disconnectedCallback() {
        pubsub.unregister('selected', this.eventFiredCallback );
        this.accountName=null;
        
    }

    @api
refresh() {
    return refreshApex(this.contactList); 
}


contactList;
@wire(getContacts,{accountID:'$account'})
wiredAccounts(contactList) {
    if(this.contactList===null) {
        this.contactList=undefined;
        this.contacts=undefined;
        this.accountName=undefined;
        return;
    }
       this.contactList = contactList;
    //this.accountName=this.contactList.data ? this.contactList.data[0].Account.Name :null;
       const { data, error } = contactList;
    if (data) {
    this.contacts = JSON.parse(JSON.stringify(data));
        console.log('Contacts',this.contacts);
        this.error = undefined;
        }
    else if (error) {
        this.error = error;
        console.log(this.error);
        this.contacts = undefined;
    }
}  

handleClick(){
 let contactRow={};
  contactRow =  {
       Id:"test",
        Title:"",
        AccountId: this.contacts[0].AccountId,
        FirstName: "",
        LastName: "",
        
        };
     
     // this.contacts.push(contactRow);

  this.contacts= [...this.contacts, contactRow ];
      console.log('This is the new list',this.contacts);
}

}

 
Ugur KayaUgur Kaya
Try setting the contact by using JSON.parse(JSON.stringify()) as well after adding the empty line
Nitesh Jain 35Nitesh Jain 35
hi Ugur, No success.
However it seems like the its always going to add the empty row at top Account and not getting the conext of current event .... For an example 
When I click the account 'AA-Nitesh Account Test 2'- It renders the contact list correct but when click on 'Add Row' it seems it always getting added to account 'AAAAA 1111 2' 
Examples....
This was selected as the best answer
Ugur KayaUgur Kaya
Can you try with  @track contacts instead of  @track Contacts;
Amaefule ChigozieAmaefule Chigozie
Facing same issue also 
Whatsapp status video (https://newwhatsappstatusvideo.com/)  new whatsapp video (https://newwhatsappstatusvideo.com/love-whatsapp-status-video/
Nitesh Jain 35Nitesh Jain 35
@ugur Kaya
Perfect .. Thank you .. It was really a silly mistake :)