9

I started writing LWCs, does anyone have an opinion on when to use @wire vs calling it imperatively?

Given that it appears that you can set cacheable for both, but due to the requirement for this with @wire, you can't do dml through @wire. It seems like imperatively you can do everything you want and its simpler to just use a single method to call apex.

What am I missing? Outside of saving a couple lines of code when you're sure the apex class will return what you need, whats the value in using @wire?

4 Answers 4

18

Wire methods take care of the entire life cycle of an attribute when it changes, including fetching calling the method, updating the attribute, and and refreshing the UI, all in often a single line of code (or just a few for custom error handling). While you could do all this imperatively, it would require significant amounts of code. In other words, yes, wire methods are basically just a "shortcut" for calling Apex imperatively, but you should not discount those savings, which could easily be hundreds of lines of code in a large component. Also, specifically, the wired method approach means you don't need to write custom setters to make sure the method is called every time the attribute is updated, or remember to call the method imperatively every time. This centralizes calling the method to a single location, making it much less likely you'll forget to call the method when appropriate.

3

Calling imperatively is the way to go when you want to call an Apex method on demand. Some use cases: On a LWC Button click, perform custom validation of related data on a record page, send related data to an external system, show a custom toast to user based on results in Apex, etc.

1
  • Thanks for providing practical examples!
    – Bahman.A
    Nov 25, 2020 at 23:26
2

I have found @wire is especially useful when you want to get a single or list of records without modifying any of the return values.

Think of using force:hasRecordId and using LDS for example, you can do this with less code with @wire now.

LWC docs use of recordId

0

Per documentation(https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.apex_call_imperative)

  • To call a method that isn’t annotated with cacheable=true, which includes any method that inserts, updates, or deletes data.
  • To control when the invocation occurs.
  • To work with objects that aren’t supported by User Interface API, like Task and Event.
  • To call a method from an ES6 module that doesn’t extend LightningElement

You must log in to answer this question.

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