LearnFrenzy
Sign in Take a free test

Salesforce LWC interview · Set 5 of 6

LWC Coding Interview Questions (Build It Live)

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

Live-build ready

Each component shows the full loop: reactive data, user input, server calls, refresh, errors and events. Practise building two or three of these from scratch before an interview.

  • Data UIsSearch, datatable, pagination and banners.
  • InputsDependent picklists and flow validation.
  • ActionsConfirm-delete and parent–child events.

Many Salesforce interviews include a live build: “create a component that searches contacts” or “show related cases in a table with actions”. Each solution below is complete and production-minded — debounced, secure, with loading and error states.

A text input updates a reactive search term after a 300 ms pause; a cacheable Apex method returns matching contacts; the template shows loading, empty and result states.

// contactSearch.js
import { LightningElement, wire } from 'lwc';
import searchContacts from '@salesforce/apex/ContactSearchController.search';

export default class ContactSearch extends LightningElement {
    searchTerm = '';
    delayTimeout;

    @wire(searchContacts, { term: '$searchTerm' }) contacts;

    handleInput(event) {
        const value = event.target.value;
        clearTimeout(this.delayTimeout);
        this.delayTimeout = setTimeout(() => { this.searchTerm = value; }, 300);
    }
    get hasResults() { return this.contacts.data?.length > 0; }
}

// ContactSearchController.cls
public with sharing class ContactSearchController {
    @AuraEnabled(cacheable=true)
    public static List<Contact> search(String term) {
        if (String.isBlank(term) || term.length() < 2) return new List<Contact>();
        String likeTerm = '%' + term + '%';
        return [SELECT Id, Name, Email, Phone FROM Contact WHERE Name LIKE :likeTerm WITH USER_MODE LIMIT 20];
    }
}

2. Show an Account's open Cases in a datatable with a row action.

Wire the cases, define columns with a row action, handle the action imperatively and refresh the wired data.

const COLUMNS = [
    { label: 'Case', fieldName: 'CaseNumber' },
    { label: 'Subject', fieldName: 'Subject' },
    { label: 'Priority', fieldName: 'Priority' },
    { type: 'action', typeAttributes: { rowActions: [{ label: 'Escalate', name: 'escalate' }] } },
];

export default class AccountCases extends LightningElement {
    @api recordId;
    columns = COLUMNS;
    wiredResult;
    cases = [];

    @wire(openCases, { accountId: '$recordId' })
    wired(result) {
        this.wiredResult = result;
        if (result.data) this.cases = result.data;
    }

    async handleRowAction(event) {
        if (event.detail.action.name === 'escalate') {
            await escalate({ caseId: event.detail.row.Id });
            await refreshApex(this.wiredResult);
        }
    }
}

<!-- template -->
<lightning-datatable key-field="Id" data={cases} columns={columns}
                     hide-checkbox-column onrowaction={handleRowAction}></lightning-datatable>

3. Build dependent picklists (Country → State) without Apex.

Use getObjectInfo for the record type and getPicklistValuesByRecordType; the dependent field's controllerValues map tells you which states belong to the chosen country.

@wire(getObjectInfo, { objectApiName: ACCOUNT }) objectInfo;

@wire(getPicklistValuesByRecordType, { objectApiName: ACCOUNT, recordTypeId: '$objectInfo.data.defaultRecordTypeId' })
picklists({ data }) {
    if (!data) return;
    this.countryOptions = data.picklistFieldValues.Country__c.values;
    this.stateField = data.picklistFieldValues.State__c;
}

handleCountry(event) {
    this.country = event.detail.value;
    const key = this.stateField.controllerValues[this.country];
    this.stateOptions = this.stateField.values.filter(v => v.validFor.includes(key));
}

4. Create a reusable confirm-before-delete button.

Wrap LightningConfirm and deleteRecord, then fire an event so the parent can refresh.

import { LightningElement, api } from 'lwc';
import LightningConfirm from 'lightning/confirm';
import { deleteRecord } from 'lightning/uiRecordApi';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';

export default class DeleteButton extends LightningElement {
    @api recordId;
    @api label = 'Delete';

    async handleClick() {
        const ok = await LightningConfirm.open({ message: 'This cannot be undone. Delete?', label: 'Confirm delete', theme: 'error' });
        if (!ok) return;
        try {
            await deleteRecord(this.recordId);
            this.dispatchEvent(new ShowToastEvent({ title: 'Deleted', variant: 'success' }));
            this.dispatchEvent(new CustomEvent('deleted', { detail: { recordId: this.recordId } }));
        } catch (e) {
            this.dispatchEvent(new ShowToastEvent({ title: 'Delete failed', message: e.body?.message, variant: 'error' }));
        }
    }
}

5. Build a simple client-side paginated list.

Keep all rows, compute the visible slice in a getter, and disable buttons at the ends. For large data, paginate on the server with LIMIT/OFFSET or keyset queries.

pageSize = 10;
page = 1;

get totalPages() { return Math.max(1, Math.ceil(this.rows.length / this.pageSize)); }
get visibleRows() {
    const start = (this.page - 1) * this.pageSize;
    return this.rows.slice(start, start + this.pageSize);
}
get isFirst() { return this.page === 1; }
get isLast() { return this.page === this.totalPages; }
previous() { if (!this.isFirst) this.page--; }
next() { if (!this.isLast) this.page++; }

6. Build a record-page component that shows a warning banner for high-value Opportunities.

Use LDS (no Apex) to read Amount and Stage, compute visibility in getters, and import field references.

import AMOUNT from '@salesforce/schema/Opportunity.Amount';
import STAGE from '@salesforce/schema/Opportunity.StageName';

export default class HighValueBanner extends LightningElement {
    @api recordId;
    @wire(getRecord, { recordId: '$recordId', fields: [AMOUNT, STAGE] }) opp;

    get showBanner() {
        const amount = getFieldValue(this.opp.data, AMOUNT) || 0;
        const stage = getFieldValue(this.opp.data, STAGE);
        return amount >= 1000000 && stage !== 'Closed Won' && stage !== 'Closed Lost';
    }
}

7. Build a counter child that tells the parent its value.

The classic communication exercise: buttons update local state, an event reports the new value, and the parent can reset it through an @api method.

// counter.js
export default class Counter extends LightningElement {
    count = 0;
    increment() { this.count++; this.notify(); }
    decrement() { if (this.count > 0) { this.count--; this.notify(); } }
    @api reset() { this.count = 0; this.notify(); }
    notify() { this.dispatchEvent(new CustomEvent('countchange', { detail: this.count })); }
}

<!-- parent -->
<c-counter lwc:ref="counter" oncountchange={handleCount}></c-counter>

8. Build a screen-flow component that validates an input.

Expose @api properties to Flow, report changes with FlowAttributeChangeEvent, and implement @api validate() so Flow blocks Next when invalid.

import { FlowAttributeChangeEvent } from 'lightning/flowSupport';

export default class PanInput extends LightningElement {
    @api pan = '';
    handleChange(event) {
        this.pan = event.target.value.toUpperCase();
        this.dispatchEvent(new FlowAttributeChangeEvent('pan', this.pan));
    }
    @api validate() {
        const ok = /^[A-Z]{5}[0-9]{4}[A-Z]$/.test(this.pan);
        return ok ? { isValid: true } : { isValid: false, errorMessage: 'Enter a valid PAN, e.g. ABCDE1234F' };
    }
}

Remember

Key points

  • Debounce search inputs

    Avoid a server call per keystroke.

  • refreshApex after writes

    Keep wired lists current.

  • LDS when possible

    No Apex for single-record reads.

  • Show every state

    Loading, empty, error and data.

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 How would you add sorting to the datatable? Intermediate

    Set sortable: true on columns, handle onsort, sort a copy of the data by the field and direction, and set sorted-by and sorted-direction.

  2. 2 How do you support inline editing in lightning-datatable? Intermediate

    Mark columns editable, handle onsave with event.detail.draftValues, save with updateRecord or Apex, then clear drafts and refresh.

  3. 3 How do you make the search work offline-friendly or cached? Advanced

    Cacheable Apex results are stored client-side; repeated searches for the same term reuse them until the cache expires or is refreshed.

  4. 4 How do you show a spinner during an imperative call? Basic

    Set isLoading = true before the await and false in finally, and render lightning-spinner with lwc:if.

  5. 5 How do you pass the recordId to a quick action LWC? Basic

    Declare @api recordId; record-page quick actions set it automatically (read it after connectedCallback for headless actions).

  6. 6 How would you upload a file from LWC? Intermediate

    Use lightning-file-upload with record-id; files attach to the record as ContentDocuments without custom Apex.

Preparing with friends?

Share this page with your study group or placement batch.

Search LearnFrenzy

Esc

Quick links