0

How can I use refreshApex in handleSave() with the following code


JS

import { LightningElement,track,wire } from 'lwc';
import { getRecord, getFieldValue } from "lightning/uiRecordApi";
import { refreshApex } from '@salesforce/apex';

import getContacts from '@salesforce/apex/DemoController3.getContacts';
import updateContact from '@salesforce/apex/DemoController3.updateContact';

export default class demo3 extends LightningElement {
    
    @track optionsArray = [];   
    contactListReceived = new Map();
    @track resultArray = [];
    @track isEdited = false;
    @track toggleSaveLabel = 'Save';

    connectedCallback(){
       
        getContacts()
        .then(response=>{   
            console.log('Response',response);
        
            response.forEach( item =>{
                this.optionsArray.push({ label : item.Name , value : item.Id })
                this.contactListReceived.set(item.Id, item);

                //Add Contact empty array in result variable
                var result ={
                    // Id:'',
                    FirstName:'',
                    LastName:'',
                    Phone:'',
                    Email:'',
                    Account:''
                };
                this.resultArray.push(result);

            })
            console.log('Contact Map: ', this.contactListReceived);
        }) 
    }

    handleChangedValue(event){
        var value = event.detail.value;
        var rowIndex = parseInt(event.target.dataset.index); 
        // this.rowIndex = event.target.dataset.index; 
        console.log('ID',rowIndex);        
        // console.log('ID',typeof(this.rowIndex));  
        console.log('Value',value);  

        //Set values in the result array
        var theSelectedContactInfo = this.contactListReceived.get(value);
        var result = {
            Id : theSelectedContactInfo.Id,
            FirstName : theSelectedContactInfo.FirstName,
            LastName:theSelectedContactInfo.LastName,
            Phone:theSelectedContactInfo.Phone,
            Email:theSelectedContactInfo.Email,
            Account:theSelectedContactInfo.Account.Name
        };
        console.log('AccName',result.Account);
        this.resultArray[rowIndex] =  result;
    }
   
    updateValue(event){
        let fields = event.target.dataset.field;

        let element = this.resultArray.find(ele  => ele.Id === event.target.dataset.id);

        element[fields] = event.target.value;

        this.resultArray = [...this.resultArray];

        console.log(JSON.stringify(this.resultArray));
    }

    handleSave(event) {
        console.log('Array list :', this.resultArray);
        console.log('Array list :', this.resultArray.Id);

        let saveRec=[];
        for(let i=0;i<this.resultArray.length;i++){

            if(this.resultArray[i].Id != null){
                saveRec.push(this.resultArray[i]);
            }
        }
        updateContact ({conData: saveRec})
        .then(result => {
            console.log('Result',JSON.stringify(result));
            return refreshApex(this.getContacts());
        })
        .catch(error => {
            console.log('Error',JSON.stringify(error));
        })
    }

    handleResetAll(){
        this.template.querySelectorAll('lightning-input').forEach(element => {
         
            element.value = null;

        });
    }

}

HTML

<template>
  <lightning-card title="Contact Details" icon-name="standard:contact_list">
    <div class="slds-box slds-theme_default">
      <table class="slds-table slds-table_cell-buffer slds-table_bordered slds-table_col-bordered">
        <thead>
          <tr>
            <th class="" scope="col">
              <div class="slds-truncate" title="Contact Name">Contact Name</div>
            </th>
            <th class="" scope="col">
              <div class="slds-truncate" title="First Name">First Name</div>
            </th>
            <th class="" scope="col">
              <div class="slds-truncate" title="Last Name">Last Name</div>
            </th>
            <th class="" scope="col">
              <div class="slds-truncate" title="Phone">Phone</div>
            </th>
            <th class="" scope="col">
              <div class="slds-truncate" title="Email">Email</div>
            </th>
            <th class="" scope="col">
              <div class="slds-truncate" title="Account Name">Account Name</div>
            </th>
          </tr>
        </thead>
        <tbody>
          <template for:each={resultArray} for:item="con" for:index="index">
            <tr key={con.Id}>
              <td>
                <lightning-combobox placeholder="Select Contact" options={optionsArray} onchange={handleChangedValue}
                  data-index={index}>
                </lightning-combobox>
              </td>
              <td>
                <div class="slds-p-around_medium lgc-bg">
                  <lightning-input type="text" value={con.FirstName} onchange={updateValue}
                    data-field="FirstName" data-id={con.Id}>
                  </lightning-input>
                </div>
              </td>
              <td>
                <div class="slds-p-around_medium lgc-bg">
                  <lightning-input type="text" value={con.LastName} onchange={updateValue}
                    data-field="LastName" data-id={con.Id}>
                  </lightning-input>
                </div>
              </td>
              <td>
                <div class="slds-p-around_medium lgc-bg">
                  <lightning-input type="text" value={con.Phone} onchange={updateValue} data-field="Phone" data-id={con.Id}>
                  </lightning-input>
                </div>
              </td>
              <td>
                <div class="slds-p-around_medium lgc-bg">
                  <lightning-input type="text" value={con.Email} onchange={updateValue} data-field="Email" data-id={con.Id}>
                  </lightning-input>
                </div>
              </td>
              <td>
                <!-- <div class="slds-p-around_medium lgc-bg">
                  <lightning-input type="text" value={con.Account} disabled=""></lightning-input>
                </div> -->
                <div class="slds-p-around_medium lgc-bg">
                  <lightning-input type="text" value={con.Account} onchange={updateValue} data-field="Account" data-id={con.Id} ></lightning-input>
                </div>
              </td>
            </tr>
          </template>
        </tbody>
      </table>
      <lightning-layout-item size="12" class="slds-align_absolute-center slds-p-top_small">
        <lightning-button type="submit" variant="brand" label="Save" onclick={handleSave}></lightning-button><br>
        <lightning-button type="Cancel"  label="Cancel" onclick={handleResetAll}></lightning-button>
      </lightning-layout-item>
    </div>
  </lightning-card>
</template>
0

2 Answers 2

0

I haven't tried the code but you probably need to use wire something like this to refresh the data:

refreshTable;
@wire(getContacts)
wiredData(response) {

    this.refreshTable = response;
    let { data, error } = response;
    return refreshApex(this.refreshTable);

}

You can also specify error handling here if you need.

At other places, where you are specifying success you can call below method:

handleSuccess() {
    return refreshApex(this.refreshTable);
}
0

Documentation states (emphasis mine):

Call this method to query the server for updated data returned by Apex, and refresh the cache of a wired property.

Since you're calling the apex method imperatively, you cannot use refreshApex.
You could extract the logic implemented in the than of getContacts() in a method, i.e. handleContacts() than in handleSave you can just call them:

updateContact ({conData: saveRec})
.then(result => {
    console.log('Result',JSON.stringify(result));
    this.getContacts()
    .then((contacts) => {
        this.handleContacts(contacts);
    });
})

Anyway the handling of getContacts() has an error: you never empty resultArray, so if in the connectedCallback you put 2 items in that array, then you modify a record and call getContacts() again, you'll have 4 items. You can declare a new array in the method, fill it, then associate to resultArray:

connectedCallback(){
    getContacts()
    .then((contacts) => {
        this.handleContacts(contacts);
    }) 
}

handleContacts(contacts) {
    console.log('Response', contacts);
    const options = [];
    const resultList = [];
    contacts.forEach(item =>{
        options.push({ label : item.Name , value : item.Id });
        this.contactListReceived.set(item.Id, item);

        //Add Contact empty array in result variable
        const result = {
            // Id:'',
            FirstName:'',
            LastName:'',
            Phone:'',
            Email:'',
            Account:''
        };
        resultList.push(result);

    });
    this.optionsArray = options;
    this.resultArray = resultList;
    console.log('Contact Map: ', this.contactListReceived);
}

By the way, consider using let and const instead of var.

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