Tuesday, March 7, 2023

Solution to overcome Heap Size error in Salesforce

When building Lightning Web Components (LWC), we may encounter the "Total heap size as 12 MB" error when working with large data sets or complex logic. This error occurs when the total size of data stored in memory (heap) exceeds 12 MB. To overcome this error, we can implement the following best practices: Use @wire to retrieve data from Apex instead of retrieving it directly in the component. This allows Salesforce to handle the data retrieval and pagination, reducing the amount of data stored in memory. Use LightningDatatable with pagination to avoid loading all data at once. Use track decorators to prevent unnecessary re-renders of the component. Avoid storing large amounts of data in arrays or objects, and use iterators to process the data in smaller chunks. Use a setTimeout function to break up long-running operations into smaller chunks and avoid blocking the main thread. Use @api to pass data between components instead of storing it in the component. Here's an example code that demonstrates some of these best practices: In this example, we're using @wire to retrieve contacts from an Apex controller. We're then using LightningDatatable to display the data with pagination. We're also using @track to ensure that only the changed data is re-rendered, and we're storing the data in an array with a getter that is only called once when the component is initialized. By following these best practices, we can reduce the amount of data stored in memory and avoid the "Total heap size as 12 MB" error in our LWC.

0 comments:

Post a Comment