[SalesForce] refreshApex in LWC not working outside of Apex method call promise

In my LWC I have:

wiredResults;


@wire(getSObjectsForTable, {stepId: '$stepId', objectApiName: '$objectName'})
getSObjectsForTable(result){
    this.wiredResults = result;
    if(result.data){
        console.log(result.data);
        this.tableData = getTableData(result.data);
        this.tableColumns = getColumns(this.tableData);
    } else if(result.error){
        console.log(result.error);
        let toastEvent = new ShowToastEvent({
            title: 'Error',
            message: 'Error retrieving records: ' + result.error,
            variant: 'error'
        });
        this.dispatchEvent(toastEvent);
    }
    this.tableLoaded = true;
}

I have a save and cancel button that fires events where I want to do refreshApex just to grab fresh data from the server.

My save:

saveCriteria(){
    let criteriaToSave = [];
    //reassemble drill up/down fields on the criteria
    for(let i = 0; i < this.tableData.length; i++){
        criteriaToSave.push(parseObjectFields(this.tableData[i]));
    }
    console.log(JSON.stringify(criteriaToSave));
    //pass tableData to apex to save.
    saveCriteriaUpdates({criteriaJSON: JSON.stringify(criteriaToSave), criteriaApiName: this.objectName})
        .then(result => {
            console.log(result);
            this.showButtons = false;
            return refreshApex(this.wiredResults);
            //Show toast on success/error
        }).catch(error => {
            console.log(JSON.stringify(error));
            //Show toast on error
        });
}

This works. The refresh apex actually causes the wire function to execute again.

My cancel:

cancelUpdates(){
    this.showButtons = false;
    refreshApex(this.wiredResults);
}

This does not work. I have tried returning the refreshApex in the cancel as well with no luck. It seems to be fine when called in the promise of an Apex method call… but not working when just… called. It just does nothing, there aren't even errors in my wire function, it does not refresh it at all.

How can I do a refreshApex on button click outside of an Apex method call promise?

Best Answer

This is happening because the underlying cached data has not changed. The javascript wire method will only be called if it detects a change in the data returned.

Related Topic