# Data access, refreshing and cross-component messaging

Target: Spring '26 (API 66.0). Sources: [Work with Salesforce Data](https://developer.salesforce.com/docs/platform/lwc/guide/data-guidelines.html), [RefreshView API](https://developer.salesforce.com/docs/platform/lwc/guide/data-refreshview.html), [`lightning/uiGraphQLApi`](https://developer.salesforce.com/docs/platform/lwc/guide/reference-graphql-wire-adapter.html), [Lightning Message Service](https://developer.salesforce.com/docs/platform/lwc/guide/use-message-channel.html).

## 1. The ladder, in order

| Rung | API | Use it for | Cost |
|---|---|---|---|
| 1 | `lightning-record-form`, `-view-form`, `-edit-form` | Show or edit one record's fields | Zero Apex, FLS and layout handled |
| 2 | `@wire(getRecord, …)` + `getFieldValue`; `createRecord`/`updateRecord`/`deleteRecord` from `lightning/uiRecordApi` | Reading and writing one record with your own markup | Cached in LDS, reactive |
| 3 | `getObjectInfo`, `getPicklistValues`, `getPicklistValuesByRecordType` (`lightning/uiObjectInfoApi`) | Schema and picklists | Cached, record-type aware |
| 4 | `getRelatedListRecords` (`lightning/uiRelatedListApi`) | Related lists as the layout defines them | Cached |
| 5 | `@wire(graphql, { query: gql\`…\` })` (`lightning/uiGraphQLApi`) | Several objects, filters and pagination in one shaped read | Cached, no Apex |
| 6 | Apex `@AuraEnabled(cacheable=true)` via `@wire` | Aggregates, joins and filters the UI API cannot express | Your code to secure and test |
| 7 | Apex imperative `await method({…})` | Every mutation with business logic, callouts or multiple objects | Your code, plus the refresh question below |

Do not skip rungs for familiarity. "We always use Apex" is how a record page ends up with six extra server round trips and its own FLS bugs.

## 2. GraphQL wire — the shape that works

```js
import { LightningElement, wire } from 'lwc';
import { gql, graphql } from 'lightning/uiGraphQLApi';

export default class OpenOrders extends LightningElement {
    orders = [];
    error;

    @wire(graphql, {
        query: gql`
            query openOrders {
                uiapi {
                    query {
                        Order__c(where: { Status__c: { ne: "Closed" } }, first: 50,
                                 orderBy: { CreatedDate: { order: DESC } }) {
                            edges {
                                node {
                                    Id
                                    Name { value }
                                    Total__c { value, displayValue }
                                }
                            }
                        }
                    }
                }
            }
        `
    })
    wiredOrders({ data, errors }) {
        this.orders = data?.uiapi?.query?.Order__c?.edges?.map((e) => e.node) ?? [];
        this.error = errors;
    }
}
```

Field values arrive as `{ value, displayValue }` objects — map them in the getter, not in the template. Variables use `$` bindings on the wire config exactly like other wires.

## 3. Refreshing after a change

| What changed | Call | Notes |
|---|---|---|
| Data provisioned by a **wired Apex** method | `refreshApex(this.wiredResult)` | Keep the whole wire result (`this.wiredResult = result`) in the wired function, not just `data` |
| A **record** that LDS has cached, changed by Apex or an integration | `await notifyRecordUpdateAvailable([{ recordId }])` | Marks it stale so every `getRecord`/`record-form` on the page refetches. Replaces the deprecated `getRecordNotifyChange` |
| A whole **view**, including standard and Aura components around you | `this.dispatchEvent(new RefreshEvent())` from `lightning/refresh` | The container coordinates; participating components still do their own `refreshApex`/`notifyRecordUpdateAvailable` |
| A **list** the user just filtered | Nothing — re-run the imperative call | Do not fake reactivity by reassigning wire parameters |

After `updateRecord` from `lightning/uiRecordApi` you usually need no refresh at all: LDS updates every subscriber. That is a reason to prefer rung 2 over Apex mutations.

## 4. Imperative calls: debounce, cancel, guard

```js
handleSearch(event) {
    const term = event.target.value;
    window.clearTimeout(this.timer);
    this.timer = window.setTimeout(async () => {
        if (term.length < 3) { this.results = []; return; }
        this.busy = true;
        try {
            this.results = await searchOrders({ term });
        } catch (e) {
            this.error = e;
        } finally {
            this.busy = false;
        }
    }, 300);
}
```

Clear the timer in `disconnectedCallback`. Never call Apex on every keystroke, and never let two in-flight searches race — keep a request token and ignore stale responses if the endpoint is slow.

## 5. Lightning Message Service

```js
// publisher
import { publish, MessageContext } from 'lightning/messageService';
import ORDER_SELECTED from '@salesforce/messageChannel/Order_Selected__c';

@wire(MessageContext) messageContext;

notify(orderId) {
    publish(this.messageContext, ORDER_SELECTED, { orderId });
}
```

```js
// subscriber
import { subscribe, unsubscribe, MessageContext, APPLICATION_SCOPE } from 'lightning/messageService';

connectedCallback() {
    this.subscription = subscribe(this.messageContext, ORDER_SELECTED,
        (msg) => { this.orderId = msg.orderId; }, { scope: APPLICATION_SCOPE });
}

disconnectedCallback() {
    unsubscribe(this.subscription);
    this.subscription = null;
}
```

The channel is metadata (`Order_Selected__c.messageChannel-meta.xml`) with `isExposed` and declared `lightningMessageFields` — treat it as a versioned contract between components, not a dumping ground. `APPLICATION_SCOPE` crosses console tabs; leave it off when the message should stay inside the active tab.

## 6. Error shapes

Apex and LDS errors arrive differently. Flatten once:

```js
export function reduceErrors(errors) {
    return (Array.isArray(errors) ? errors : [errors])
        .filter(Boolean)
        .flatMap((e) => {
            if (Array.isArray(e.body)) return e.body.map((b) => b.message);
            if (e.body?.pageErrors?.length) return e.body.pageErrors.map((p) => p.message);
            if (e.body?.fieldErrors) return Object.values(e.body.fieldErrors).flat().map((f) => f.message);
            if (typeof e.body?.message === 'string') return [e.body.message];
            if (typeof e.message === 'string') return [e.message];
            return ['Unknown error'];
        });
}
```

Show the flattened message inline near the action and keep the raw error for the console; an `AuraHandledException` message is already user-safe, an LDS `fieldErrors` message is not always.
