LearnFrenzy
Sign in Take a free test

Salesforce LWC interview · Set 3 of 6

Working with Salesforce Data: Wire, LDS and Apex

  • 6 follow-up questions
  • 4 key points
  • Code examples
Test yourself

LDS first, Apex when needed

Use Lightning Data Service for single records and standard forms, wire cacheable Apex for reactive reads, imperative Apex for writes, and refresh caches deliberately.

  • LDSRecord forms, getRecord and uiRecordApi.
  • ApexWire vs imperative and cacheable rules.
  • FreshnessrefreshApex, notifyRecordUpdateAvailable and errors.

Most LWC bugs are data bugs: stale values, extra server calls, missing errors. Interviewers check whether you use Lightning Data Service first, wire or imperative Apex appropriately, and refresh caches correctly.

1. What is Lightning Data Service and why use it first?

LDS loads, caches and saves records without Apex. Components that show the same record share one cached copy, stay in sync automatically, and respect sharing and field-level security. Use base components (lightning-record-form, lightning-record-edit-form) or lightning/uiRecordApi adapters before writing Apex.

<lightning-record-edit-form object-api-name="Case" record-id={recordId} onsuccess={handleSaved}>
    <lightning-input-field field-name="Subject"></lightning-input-field>
    <lightning-input-field field-name="Priority"></lightning-input-field>
    <lightning-button type="submit" label="Save"></lightning-button>
</lightning-record-edit-form>

2. How do you read a record with getRecord?

Wire getRecord with the record Id and imported field references (so the compiler checks field names and the fields are protected from deletion). Read values with getFieldValue.

import { LightningElement, api, wire } from 'lwc';
import { getRecord, getFieldValue } from 'lightning/uiRecordApi';
import NAME from '@salesforce/schema/Account.Name';
import INDUSTRY from '@salesforce/schema/Account.Industry';

export default class AccountHeader extends LightningElement {
    @api recordId;
    @wire(getRecord, { recordId: '$recordId', fields: [NAME, INDUSTRY] }) account;

    get name() { return getFieldValue(this.account.data, NAME); }
    get industry() { return getFieldValue(this.account.data, INDUSTRY); }
}

3. Wire vs imperative Apex — when do you use each?

Wire is reactive and cached: it runs when its $-prefixed parameters change and requires @AuraEnabled(cacheable=true), so the method must not change data. Imperative calls run when you call them (button clicks, saves), can perform DML (non-cacheable) and give you full control over timing and errors.

// Apex
public with sharing class CaseController {
    @AuraEnabled(cacheable=true)
    public static List<Case> openCases(Id accountId) {
        return [SELECT Id, CaseNumber, Subject, Priority FROM Case
                WHERE AccountId = :accountId AND IsClosed = false WITH USER_MODE ORDER BY CreatedDate DESC LIMIT 50];
    }
    @AuraEnabled
    public static void escalate(Id caseId) {
        update as user new Case(Id = caseId, Priority = 'High');
    }
}

// LWC
import openCases from '@salesforce/apex/CaseController.openCases';
import escalate from '@salesforce/apex/CaseController.escalate';

@wire(openCases, { accountId: '$recordId' }) cases;          // reactive read

async handleEscalate(event) {                                  // imperative write
    await escalate({ caseId: event.target.dataset.id });
}

4. How do you refresh wired data after a change?

Keep the whole wired result (not just data) and call refreshApex(this.wiredResult) after an imperative save. For LDS records changed outside LDS, call notifyRecordUpdateAvailable([{ recordId }]) so every component showing that record updates.

import { refreshApex } from '@salesforce/apex';
import { notifyRecordUpdateAvailable } from 'lightning/uiRecordApi';

wiredCases;
@wire(openCases, { accountId: '$recordId' })
wiredOpenCases(result) {
    this.wiredCases = result;                 // keep the provisioned value
    if (result.data) this.cases = result.data;
}

async handleEscalate(event) {
    const caseId = event.target.dataset.id;
    await escalate({ caseId });
    await notifyRecordUpdateAvailable([{ recordId: caseId }]);
    await refreshApex(this.wiredCases);
}

5. How do you handle errors from wire and Apex calls?

Wire results have data or error; imperative calls throw. Errors arrive in several shapes (body.message, pageErrors, fieldErrors) — normalise them with a small helper and show a toast or inline message. Throw AuraHandledException in Apex to send a clean message.

import { ShowToastEvent } from 'lightning/platformShowToastEvent';

function reduceErrors(error) {
    const errors = Array.isArray(error) ? error : [error];
    return errors.filter(Boolean).map(e => e.body?.message || e.message || 'Unknown error').join(', ');
}

showError(error) {
    this.dispatchEvent(new ShowToastEvent({ title: 'Something went wrong', message: reduceErrors(error), variant: 'error' }));
}

6. Wire a function instead of a property — why?

Wiring a function lets you transform data (map fields, compute flags), handle errors and keep the full result for refreshApex — all in one place, instead of complex getters reading this.prop.data.


7. How do you create or update records without Apex?

Use createRecord, updateRecord and deleteRecord from lightning/uiRecordApi; they update the LDS cache automatically and respect user permissions.

import { updateRecord } from 'lightning/uiRecordApi';
import ID from '@salesforce/schema/Case.Id';
import STATUS from '@salesforce/schema/Case.Status';

async closeCase() {
    await updateRecord({ fields: { [ID.fieldApiName]: this.recordId, [STATUS.fieldApiName]: 'Closed' } });
}

8. What is the GraphQL wire adapter?

lightning/uiGraphQLApi lets a component query several objects, related records, filters and pagination in one request through LDS — fewer round trips and no Apex for many read scenarios.


Remember

Key points

  • cacheable = read-only

    No DML in wired Apex.

  • $ makes parameters reactive

    Re-runs when the value changes.

  • Store the wired result

    refreshApex needs it.

  • Import field references

    Compile-time checks and safe deletes.

Interview drill

Follow-up questions

What the interviewer asks after your first answer. Turn on practice mode, answer each one aloud, then reveal.

  1. 1 Why does my wired Apex method not update after I edit the record? Intermediate

    Wired Apex results are cached; call refreshApex with the stored result after changes.

  2. 2 Can a wired method take an object parameter? Intermediate

    Yes, but reactivity triggers only when the object reference changes; pass primitives or create a new object to trigger a refresh.

  3. 3 What does @AuraEnabled(continuation=true) do? Advanced

    It allows long-running callouts from Apex called by LWC without holding a server thread, using the Continuation class.

  4. 4 How do you get picklist values in LWC? Basic

    Wire getPicklistValues (with a record type Id from getObjectInfo) from lightning/uiObjectInfoApi.

  5. 5 How do you show a data table of records? Basic

    Use lightning-datatable with columns, data and key-field; handle row actions and inline edits with its events.

  6. 6 How do you limit server calls on a search box? Intermediate

    Debounce the input (setTimeout cleared on each keystroke, about 300 ms) before updating the reactive parameter.

Preparing with friends?

Share this page with your study group or placement batch.

Search LearnFrenzy

Esc

Quick links