You should be able to run your imperative Apex call from a getRecord adapter:
import { LightningElement, api, wire } from 'lwc';
import { getRecord } from 'lightning/uiRecordApi';
import { refreshApex } from '@salesforce/apex';
import myMethod from '@salesforce/apex/MyClass.myMethod';
export default class MyLWC extends LightningElement {
@api recordId;
result;
@wire(getRecord, { recordId: '$recordId', fields: ['Account.Id'] })
getRecordData({ error, data }) {
if (this.recordId) {
refreshApex(this.result);
this.imperativeApexFunction();
}
}
}
imperativeApexFunction() {
myMethod({ recordId: this.recordId })
.then( result => {
console.log(result);
this.result = result;
// Handle result
})
.catch( error => {
console.log(error);
// Handle error
})
}
The @wire getRecord adapter is intrinsically connected to the LDS, and will automatically run when a change is saved to the parent record, or a related child record, causing your Apex method to rerun as well
The recordId is not always set by default on page load, and it is helpful to include a check to see if there is a recordId before running your Apex method to prevent null errors