Wednesday, March 12, 2025

Synchronous vs. Asynchronous in connectedCallback() and @wire

 

Synchronous vs. Asynchronous in connectedCallback() and @wire

FeatureconnectedCallback()@wire
Execution TypeSynchronousAsynchronous
When It RunsRuns immediately when the component is inserted into the DOM.Runs asynchronously after the component is initialized.
Data FetchingCalls Apex methods imperatively, meaning it executes the function and waits for the result (Promise-based).Uses reactive data fetching, meaning data is retrieved asynchronously and updates the UI automatically when data changes.
Blocking or Non-Blocking?Blocking – It executes sequentially until it completes.Non-blocking – Data is fetched in the background and updates the component when available.

 connectedCallback() is Synchronous

  • The function inside connectedCallback() executes immediately when the component is inserted into the DOM.
  • However, if it contains an asynchronous operation (like an Apex call), the function itself is synchronous, but the Apex call is asynchronous.

Example: Synchronous Execution in connectedCallback()


connectedCallback() { console.log("Component is loaded"); // This runs synchronously }

🔄 Example: Making an Asynchronous Apex Call in connectedCallback()


connectedCallback() { getAccounts() // Asynchronous Apex call .then(result => { this.accounts = result; // Updates after response }) .catch(error => { console.error(error); }); console.log("API call initiated"); // This runs before the API call completes }

🔹 The Apex call (getAccounts()) is asynchronous, but connectedCallback() itself is synchronous.

 @wire is Asynchronous

  • The @wire decorator runs asynchronously in the background and updates the component when the data is available.
  • It does not block the component from rendering.

Example: Asynchronous Execution in @wire


@wire(getAccounts) wiredAccounts({ error, data }) { if (data) { console.log("Data received asynchronously", data); } else if (error) { console.error("Error fetching data", error); } } console.log("This executes immediately while data is being fetched");

🔹 The console log runs first, and the data arrives asynchronously.


Key Takeaways

FeatureconnectedCallback()@wire
ExecutionSynchronous (but can contain asynchronous calls)Asynchronous
Data FetchingManual, imperative (Apex call returns a Promise)Automatic, reactive
Blocking UI?Can block UI if used incorrectlyNon-blocking (fetches in the background)
When to UseExternal API calls, event listeners, manual controlSalesforce data fetching, automatic updates

Conclusion:

  • @wire is better for handling Salesforce data reactively.
  • connectedCallback() is better for initializing the component, subscribing to events, or calling external services.

No comments: