[SalesForce] Can we call LWC wire adapters imperatively

Is it possible to call a wire adapter such as getObjectInfo imperatively? I know they return void and not a Promise so surely they can't be called like an Apex method. This is the error I've been getting:

LWC component's @wire target property or method threw an error during value provisioning. Original error:
[this.callback is not a function]]

Example call I've tried:

method() {
    getObjectInfo({ objectApiName: 'Account' });
}

If this is not possible is there any way I could utilize the LDS adapters imperatively as opposed to resorting to Apex? In my case I want to retrieve a list of fields for an object, on demand.

Best Answer

No, wire methods cannot be called imperatively.

Use Apex in these scenarios:

...

To call a method imperatively, as opposed to via the wire service. You may want to call a method imperatively in response to clicking a button, or to delay loading to outside the critical path. When you call an Apex method imperatively, to refresh the data, invoke the Apex method again.

If you need to do some special handling afterwards, set this up in the wire handler:

@wire(method, params) 
 wireHandler({data,error}) {
  if(data) {
   this.handleData(data);
  }
  if(error) {
   this.handleError(error);
  }
 }

To actually trigger the call, you can set a reactive variable:

someVariable;
@wire(method, {param:'$someVariable'}) 

If you wanted to further make the call dynamic, you can do that, too!

someVariable;
someCallback;
@wire(method, {param:'$someVariable'}) 
 wireHandler({data,error}) {
  if(data) {
   this.someCallback(data);
  }
  if(error) {
   this.handleError(error);
  }
 }
 handleClick(event) {
  this.someCallback = (result) => {
   console.log(result);
  };
  this.someVariable = 'Hello World';
 }
Related Topic