If you are thinking this post is about implementing infinite scrolling behavior for lightning-datatable component, then you only got half part right. Main purpose of this blog post is to compare side by side @wire vs Imperative way of calling Apex and decide which one to use when?
In this post, you would learn
- How to call Apex in LWC using @wire
- How to call Apex in LWC by Imperative approach
- How to call Apex on component load event equivalent to init in Aura
- Why would you choose to call Apex either by @wire or Imperative Apex approach
- How to bind wrapper class in Lightning-datatable component
- How to enable infinite scrolling in Lightning-datatable by making server call
Lets start with building demo lightning-datatable component with infinite scroll effect , below code is self explanatory so I would skip code explanation part. Click here for live demo of this component and test end result yourself.
Initially , it seems everything working as expected, however after some scroll , try to search any employee name. You would observe that Salesforce never made 2nd Apex call as cacheable=true was mentioned in Apex. Salesforce is trying to save resources. You cannot use wire method if cacheable is not true. This is great caching feature, unfortunately it didn’t sufficed our need.
Let’s do one more attempt, this time we would use Imperative approach and use connectedCallback method to make Apex call on component load. @wire decorator did this automatically on component load, this time we have to make explicit call. Another change , we have done is, we marked method as cacheable=false. Click here for live demo of this component and test end result yourself.
Use below code to wrap both approach in single component