Sub topic 2
Observing Nested Changes with `@track`
Assume you know JavaScript classes, object references, spread syntax, and the HTML, JavaScript, and metadata files in a Lightning web component (LWC).
Observing nested changes with `@track`
A plain field rerenders when you assign a new value to it. @track also observes changes inside plain objects and arrays. This lets a component rerender after changing a nested property directly.
import { LightningElement, track } from 'lwc';
export default class ProfileCard extends LightningElement {
@track profile = {
name: 'Ada',
address: { city: 'London' }
};
rename() {
this.profile.name = 'Grace';
this.profile.address.city = 'Oxford';
}
}If the template reads profile.name or profile.address.city, those changes can update the rendered output.
What `@track` does not observe
@track recursively observes plain objects and arrays. It does not make every JavaScript value deeply reactive. Values such as Date, Set, Map, and instances of custom classes are not observed internally. Replace the field with a new value instead.
Also, LWC observes changes relevant to the template. Changing an object property that the template never reads does not require a visible rerender.
Exposing public properties with `@api`
@api exposes a property to a parent component. Public properties are reactive, and the parent sets them through attributes.
import { LightningElement, api } from 'lwc';
export default class InfoCard extends LightningElement {
@api heading;
@api expanded = false;
}<template>
<c-info-card heading="Release notes" expanded></c-info-card>
</template>Why a child must not change its `@api` properties
Public properties represent state owned by the parent. The child may read them, but it should not assign to them. A child that needs a change should dispatch an event and let the parent update the value.
Exercise
A child receives @api selected="false". How should it request that selected become true?
Show answer
Dispatch a custom event, such as select, and let the parent handle it and update selected.