Lightning Web Components (LWC) practice exercises
These exercises build real components on the property data model, from a simple record page component to a datatable that updates records and a component you can use in a screen flow.
All exercises use the data model from our real estate practice project: Property__c, Buyer__c, Agent__c, Property_Agent__c and Property_Offer__c. Build Task 1 of that project first (about an hour), in a free Developer Edition org. Each exercise has a level, a check so you know it works, and a model answer to open after you have tried.
Exercises
1. Show fields with getRecord
BeginnerBuild propertySummary for the property record page. Show the asking price and price per square foot using the wire adapter getRecord, without Apex.
- Add it to the property page in Lightning App Builder: it shows the values for the record you are viewing.
Show a model answer
import { LightningElement, api, wire } from 'lwc';
import { getRecord, getFieldValue } from 'lightning/uiRecordApi';
import PRICE from '@salesforce/schema/Property__c.Asking_Price__c';
import PPSF from '@salesforce/schema/Property__c.Price_per_Sq_Ft__c';
export default class PropertySummary extends LightningElement {
@api recordId;
@wire(getRecord, { recordId: '$recordId', fields: [PRICE, PPSF] }) property;
get price() { return getFieldValue(this.property.data, PRICE); }
get ppsf() { return getFieldValue(this.property.data, PPSF); }
}Importing field references makes the dependency visible to Salesforce, which stops the fields being deleted while in use. In the meta file, expose the component with the target lightning__RecordPage.
2. Offers in a datatable
BeginnerShow the property's offers in a lightning-datatable, loaded with a cacheable Apex method through @wire.
- The table lists the offers for the current property.
Show a model answer
// Apex
public with sharing class OfferController {
@AuraEnabled(cacheable=true)
public static List<Property_Offer__c> getOffers(Id propertyId) {
return [SELECT Id, Name, Offer_Amount__c, Status__c
FROM Property_Offer__c WHERE Property__c = :propertyId
WITH USER_MODE ORDER BY Offer_Amount__c DESC];
}
}
// JS
import getOffers from '@salesforce/apex/OfferController.getOffers';
@wire(getOffers, { propertyId: '$recordId' }) offers;The $ makes the parameter reactive: the wire runs again when recordId changes. Cacheable methods cannot change data.
3. Search box
IntermediateBuild a property search: a text input for the city that filters the results as the user types, waiting 300 ms after the last keystroke before calling Apex.
- Typing quickly makes one server call, not one per letter.
Show a model answer
searchKey = '';
@wire(searchProperties, { city: '$searchKey' }) results;
handleChange(event) {
window.clearTimeout(this.timer);
const value = event.target.value;
this.timer = window.setTimeout(() => { this.searchKey = value; }, 300);
}This is called debouncing. Copy the value out of the event before the timeout, because the event object should not be used later.
4. Child-to-parent event
IntermediateSplit the search into a parent list and a child propertyTile. When a tile is clicked, the child sends the property ID to the parent, which shows the details.
- Clicking a tile updates the parent's selected property.
Show a model answer
// child
handleClick() {
this.dispatchEvent(new CustomEvent('select', { detail: this.property.Id }));
}
<!-- parent template -->
<c-property-tile property={p} onselect={handleSelect}></c-property-tile>
// parent
handleSelect(event) { this.selectedId = event.detail; }Data goes down through @api properties and comes up through events. Event names must be lowercase with no "on" prefix.
5. Update a record and refresh
IntermediateAdd an "Accept" button to each offer row. It updates the status with updateRecord, shows a success or error toast, and refreshes the table.
- Accepting an offer changes its status in the table without reloading the page.
- A validation rule error appears in the toast.
Show a model answer
import { updateRecord } from 'lightning/uiRecordApi';
import { refreshApex } from '@salesforce/apex';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
async accept(offerId) {
try {
await updateRecord({ fields: { Id: offerId, Status__c: 'Accepted' } });
this.dispatchEvent(new ShowToastEvent({ title: 'Offer accepted', variant: 'success' }));
await refreshApex(this.offers);
} catch (e) {
this.dispatchEvent(new ShowToastEvent({ title: 'Could not accept', message: e.body?.message, variant: 'error' }));
}
}refreshApex needs the exact value provisioned by the wire (here this.offers). Your Apex trigger from the Apex exercises also runs, rejecting the other offers.
6. Use the component in a screen flow
AdvancedMake a component that shows a slider for the offer amount between 70% and 100% of the asking price, and use it in the offer screen flow. The flow passes in the asking price and reads back the chosen amount.
- In the flow, the component appears on the screen and the chosen amount is saved on the offer.
Show a model answer
<!-- meta xml -->
<targets><target>lightning__FlowScreen</target></targets>
<targetConfigs>
<targetConfig targets="lightning__FlowScreen">
<property name="askingPrice" type="Integer" role="inputOnly"/>
<property name="amount" type="Integer"/>
</targetConfig>
</targetConfigs>
// JS
import { FlowAttributeChangeEvent } from 'lightning/flowSupport';
@api askingPrice; @api amount;
handleChange(e) {
this.dispatchEvent(new FlowAttributeChangeEvent('amount', Number(e.target.value)));
}Telling Flow about changes with FlowAttributeChangeEvent keeps the value when the user moves between screens.
Keep going
Common questions
01Should I use getRecord or Apex?
Should I use getRecord or Apex?
Use Lightning Data Service (getRecord, updateRecord, lightning-record-form) for single records: it caches, respects security and needs no Apex. Use Apex for lists, filters and anything the UI API does not offer.
02How do I deploy these components?
How do I deploy these components?
Create them in VS Code with the Salesforce Extensions and deploy with sf project deploy start, or right-click and deploy. The Developer Console does not support LWC.