Async data in components
Learn how to fetch data in web components: start in connectedCallback, show loading and error states, abort stale requests, and build a task controller.
- 01Load data when a component connectsStart a request in
connectedCallback(), and stop the rest of the work when the element has left the page during anawait. - 02Show every state, and only the newest answerDraw loading, error, and done from one
status, and keep a slow old answer from covering a newer one. - 03Cancel what's staleAbort requests with
AbortControlleron new input and on removal, keep them through moves, and wrap it all in a task controller like@lit/task.
How do you fetch data in a web component?
The Leaf and Kettle web shop shows tasting notes under each tea. The notes live on the shop's server, so a component has to ask for them. Asking takes time. The answer may be slow. It may fail. It may come after the reader has moved on.
So when should the component ask? What should it show while it waits? And what if the answer comes too late?
Start the request when the component joins the page, in connectedCallback(). Keep a status, pending, complete, or error, and draw from it. Give each request an AbortSignal, and abort it when new input comes or the element leaves the page. Then a late answer can't cover a newer one.
Here it is in the tea kit. Its new tea-notes element loads the notes for one tea:
<tea-notes tea-id="sencha"></tea-notes><tea-notes tea-id="oolong"></tea-notes><script type="module"> import "./kitchen.js"; import "./tea-kit/index.js";</script>- Lines 1 and 2 are two
tea-notes. Eachtea-idsays which tea to load. - Line 4 loads kitchen.js, a pretend server for this page. Line 5 loads the kit.
Both notes say Loading at first. Under them, the Kitchen box lists two orders. Press Answer sencha, then Fail oolong.
The first shows Sencha: grassy and sweet. The second shows Could not load oolong. The kitchen answered 500., with a Try again button. One component, three states.
Loading sencha. The kitchen's answer moves them to complete, and a failed answer moves them to error. Each state draws its own words.Asha orders a Sencha at a busy counter. The cashier hands her a buzzer, and she sits down. When it buzzes, she picks up her tea. If the Sencha has sold out, the cashier comes to tell her. At every moment, she knows which of the three it is.
- In real life: Ordering at the counter
- In JavaScript: Starting the request
- In real life: Holding the buzzer while you wait
- In JavaScript: The pending state: Loading sencha
- In real life: The buzzer goes off, and the tea is ready
- In JavaScript: The complete state, with the notes
- In real life: The cashier says the tea is sold out
- In JavaScript: The error state, with what went wrong
Ask when you join, draw from a status, and abort what's stale. A component starts its request in connectedCallback(). It keeps pending, complete, or error in one field and draws from it. It aborts a request that new input or a removal has made useless.
How does the pretend kitchen work?
A real server answers when it's ready, so you can't choose the order of its answers. So every page here loads kitchen.js instead. It's a fake: a stand-in that really works, with no real server (test doubles). Tests fake the network the same way. Here is its fetch():
globalThis.fetch = (url, { signal } = {}) =>
new Promise((resolve, reject) => {
signal?.throwIfAborted();
const { pathname, searchParams } = new URL(url, "https://leaf-and-kettle.example");
const query = searchParams.get("q");
const label = query === null ? pathname.split("/").pop() : `search ${query}`;
const found = query === null ? teas[label] : search(query.toLowerCase());
const row = document.createElement("p");
const send = (status, json) => {
row.remove();
resolve(new Response(JSON.stringify(json), { status, headers: { "Content-Type": "application/json" } }));
};
row.append(button(`Answer ${label}`, () => send(found ? 200 : 404, found ?? {})), " ", button(`Fail ${label}`, () => send(500, {})));
board.append(row);
signal?.addEventListener("abort", () => {
if (!row.isConnected) return;
row.remove();
console.log(`The kitchen stopped ${label}`);
reject(signal.reason);
});
});- Line 1 puts the kitchen's own
fetch()in place of the browser's. - Lines 8 to 14 add a row to the board, with an Answer and a Fail button.
- Line 11 answers with a real
Response, as a server would. - Lines 15 to 20 stop the order when its signal is aborted. Line 18 prints it. Line 19 rejects with the signal's reason, as the browser's
fetch()does.
So you decide when each answer comes. Lesson 19.1 built TeaElement, and lesson 19.3 made it a controller host. This lesson ends the module with one more controller: a task.
Can connectedCallback be async?
Yes. connectedCallback() runs each time the element joins the page, and it can run more than once (lesson 3.3). The specification recommends doing setup there, rather than in the constructor (MDN). Asking for data is setup.
Nolan Lawson says an async connectedCallback() is fine (Nolan Lawson). But an async function always gives back a promise (async functions), and the browser ignores it. The browser runs the callback up to its first await, and goes on. Try it. Press Answer sencha:
<button id="remove">Remove the notes</button><script type="module"> import "./kitchen.js"; import "./tea-notes.js"; const notes = document.createElement("tea-notes"); notes.setAttribute("tea-id", "sencha"); document.body.prepend(notes); console.log("prepend() returned"); document.querySelector("#remove").addEventListener("click", () => { notes.remove(); console.log("Removed the notes"); });</script>Press Remove the notes, then Answer sencha. The notes are gone from the page, but the function goes on after its await and draws them anyway.
- Line 5 makes the notes. Line 7 puts them on the page, and line 8 prints right after.
- In the tea-notes.js tab, line 5 prints, and line 6 waits for the kitchen. Line 8 prints whether the notes are still on the page.
With Answer alone, it prints Asked the kitchen for sencha, prepend() returned, then Drew Sencha. On the page: true. prepend() returned before the notes came. Nothing waited for the promise.
Now press Run again. This time, press Remove the notes first, then Answer sencha. With No check, the last line is Drew Sencha. On the page: false. The rest of the function still ran, on notes nobody can see. With Check isConnected, it prints Stopped: sencha left the page.
class TeaNotes extends HTMLElement {
async connectedCallback() {
const id = this.getAttribute("tea-id");
this.textContent = `Loading ${id}`;
console.log(`Asked the kitchen for ${id}`);
const tea = await fetch(`/api/teas/${id}`).then((response) => response.json());
if (!this.isConnected) {
console.log(`Stopped: ${id} left the page`);
return;
}
this.textContent = `${tea.name}: ${tea.notes}`;
console.log(`Drew ${tea.name}. On the page: ${this.isConnected}`);
}
}
customElements.define("tea-notes", TeaNotes);- Line 7 reads
isConnected. It's true only while the element is in a document (MDN). - Lines 8 and 9 print why, and stop before the drawing on line 11.
A waiter takes Ravi's order and goes to brew it. While the tea brews, Ravi pays and leaves. The waiter comes back and pours the tea at an empty table. A careful waiter looks at the table first.
- In real life: Taking Ravi's order
- In JavaScript: connectedCallback() starting the fetch
- In real life: The tea brewing
- In JavaScript: The await
- In real life: Ravi paying and leaving
- In JavaScript: The notes being removed
- In real life: Looking at the table before pouring
- In JavaScript: Checking isConnected after the await
Why it matters: any line after an await can run on an element that's gone. Check after every await, or use a signal, as the next sections do. The check still lets the kitchen brew the tea. Only an abort stops that.
How do you show loading and error states?
A request is always in one of three states: waiting, done, or failed. Keep that in one field, status. Then the drawing only has to read it. Here is tea-notes on TeaElement, which calls render() after each update (lesson 19.1):
import { TeaElement } from "./tea-kit/element.js";
class TeaNotes extends TeaElement {
static attributes = { teaId: {} };
static template = `<p role="status"></p>`;
status = "pending";
connectedCallback() {
super.connectedCallback();
this.#load();
}
async #load() {
try {
const response = await fetch(`/api/teas/${this.teaId}`);
if (!response.ok) throw new Error(`The kitchen answered ${response.status}.`);
this.value = await response.json();
this.status = "complete";
} catch (error) {
this.error = error;
this.status = "error";
}
this.requestUpdate();
}
render() {
this.renderRoot.querySelector("p").textContent = {
pending: () => `Loading ${this.teaId}`,
complete: () => `${this.value.name}: ${this.value.notes}`,
error: () => `Could not load ${this.teaId}. ${this.error.message}`,
}[this.status]();
}
}
customElements.define("tea-notes", TeaNotes);- Line 4 declares the
tea-idattribute asteaId(lesson 19.2). Line 6 starts the status atpending. - Line 10 starts loading when the notes connect.
- Line 15 asks the kitchen. Line 16 throws when the answer isn't ok.
- Lines 17 and 18 keep the value and set
complete. Lines 20 and 21 keep the error and seterror. - Line 23 asks for an update, so the new state is drawn.
- Lines 27 to 31 pick the function for the status, and call it.
Line 16 matters. fetch() rejects only when it can't get an answer at all, like when the network is down. An answer of 404 or 500 still resolves, with response.ok false (MDN, and response.ok). Without line 16, the notes would try to show a failed answer as tea.
The status line has role="status", a polite live region (lesson 13.5). Screen readers announce its changes, like the notes arriving. Press Answer sencha and Fail oolong. Leave matcha alone:
<tea-notes tea-id="sencha"></tea-notes><tea-notes tea-id="oolong"></tea-notes><tea-notes tea-id="matcha"></tea-notes><script type="module"> import "./kitchen.js"; import "./tea-notes.js";</script>- Lines 1 to 3 are three notes, one for each tea.
- Line 5 loads the kitchen. Line 6 loads the tea-notes.js tab, the file above.
They show Sencha: grassy and sweet, Could not load oolong. The kitchen answered 500., and Loading matcha. One file, three states, on one page.
Why does an old answer cover a new one?
Answers don't always come back in the order you asked. A busy server can answer the first request last. Here is a smaller tea-notes that loads whenever its tea-id changes. Press Switch to oolong, then Answer oolong, then Answer sencha:
<tea-notes tea-id="sencha"></tea-notes><button id="switch">Switch to oolong</button><script type="module"> import "./kitchen.js"; import "./tea-notes.js"; document.querySelector("#switch").addEventListener("click", () => { document.querySelector("tea-notes").setAttribute("tea-id", "oolong"); });</script>Press Switch to oolong, Answer oolong, then Answer sencha. Oolong's answer comes first and shows. Then sencha's old answer comes and covers it. The notes say Sencha, but their tea-id is oolong.
- On the page, line 7 changes the notes' tea-id.
- In the tea-notes.js tab,
attributeChangedCallback()on line 4 runs for the first tea-id and for each change. Line 6 waits for the kitchen.
With No guard, it prints Showing Oolong, then Showing Sencha. The notes end on Sencha: grassy and sweet, but their tea-id is oolong. The reader asked for one tea and got another. With Ignore old answers, it prints Ignored the old answer for sencha, and Oolong stays.
tea-id was oolong.Lines 7 to 10 of the second version compare the answer's tea with the one the notes show now. That fixes the screen. But the kitchen still made a sencha nobody wanted. Lit's docs name this race as one thing its Task handles: only the newest run completes the task (Lit). The next section stops the old order itself.
How do you cancel a fetch in a web component?
With an AbortController. The JavaScript course covers it in full (AbortController and AbortSignal). In short:
- a controller makes a signal;
- you hand the signal to
fetch(); - calling
abort()on the controller makes thatfetch()reject.
Asha orders a Sencha, then changes her mind: Oolong, please. The cashier calls to the kitchen to stop the Sencha. Now the kitchen makes only the Oolong, and the wrong tea is never served.
- In real life: The cashier's order pad
- In JavaScript: The AbortController
- In real life: The order slip in the kitchen
- In JavaScript: The signal handed to fetch()
- In real life: Calling stop to the kitchen
- In JavaScript: abort()
- In real life: Asha changing her mind
- In JavaScript: A new tea-id
Here is the browser's own fetch(), on a data: URL, so no network is used:
<script type="module"> const controller = new AbortController(); const answer = fetch("data:text/plain,Sencha", { signal: controller.signal }); controller.abort(); console.log(controller.signal.aborted); try { await answer; } catch (error) { console.log(error.name); }</script>- Line 3 starts a
fetch()with the controller's signal. Line 4 aborts it at once. - Line 5 prints the signal's
aborted. Lines 6 to 10 wait for thefetch(), and print the error's name.
It prints true, then AbortError. Check the name, not the message. The DOM Standard says that abort() with no reason gives a new DOMException named AbortError (DOM). The message is up to each browser (Web IDL). So write error.name === "AbortError", and never test the words.
When should a component abort?
A component has two moments to abort. One is new input: a new tea-id makes the old answer useless. The other is leaving the page: no one will see the answer. WebComponents.Guide uses both (WebComponents.Guide). Here is the race's tea-notes with a controller. Press Switch to oolong, then Answer oolong:
<tea-notes tea-id="sencha"></tea-notes><button id="switch">Switch to oolong</button><button id="remove">Remove the notes</button><script type="module"> import "./kitchen.js"; import "./tea-notes.js"; const notes = document.querySelector("tea-notes"); document.querySelector("#switch").addEventListener("click", () => notes.setAttribute("tea-id", "oolong")); document.querySelector("#remove").addEventListener("click", () => notes.remove());</script>- In the tea-notes.js tab, line 3 keeps the controller.
- Line 6 aborts the old request. Lines 7 and 8 make a new controller for this tea.
- Line 11 hands the signal to
fetch(). - Line 14 returns quietly for an abort. An abort isn't a failure.
- Lines 19 to 21 abort when the notes leave the page.
Switch prints The kitchen stopped sencha, and sencha's buttons leave the board. Answer oolong shows Oolong: toasty, like honey. Run it again and press Remove the notes: it prints The kitchen stopped sencha too.
In the Ignore version, the kitchen still made the sencha. Here the order stops. With a real server, the browser cancels the network request (Lit). Why it matters: on a slow phone, every request you don't need slows down the ones you do.
When do you need throwIfAborted()?
fetch() watches its signal. Many other awaits don't. After an await that takes no signal, call signal.throwIfAborted(). It does nothing until the signal is aborted. Then it throws the signal's reason (MDN). Lit's docs suggest it after each such await in a task (Lit).
const controller = new AbortController();
const { signal } = controller;
signal.throwIfAborted();
console.log("Not aborted yet");
controller.abort();
try {
signal.throwIfAborted();
} catch (error) {
console.log(error.name, error === signal.reason);
}- Line 3 does nothing: the signal isn't aborted yet.
- Line 5 aborts it. Line 7 throws.
- Line 9 prints the error's name, and whether it's the signal's reason.
It prints Not aborted yet, then AbortError true.
How do you cancel requests while someone types?
A search box asks on every letter. Type oolong, and that's six requests. The JavaScript course shows how their answers can arrive out of order (search races). Here each new letter aborts the request before it. Type oolong in the box:
<tea-finder></tea-finder><script type="module"> import "./kitchen.js"; import "./tea-finder.js";</script>- In the tea-finder.js tab, line 7 calls
#find()for each letter. - Lines 11 and 12 abort the last request and make a new controller.
- Line 14 hands its signal to
fetch(). Line 17 lets an abort go quietly, and throws anything else.
It prints The kitchen stopped search o, then the same for oo, ool, oolo, and oolon. Only search oolong stays on the board. Press its Answer, and the box shows Oolong.
Can one request have two reasons to stop?
Yes. AbortSignal.any() makes one signal from several. It aborts when any of them does. AbortSignal.timeout() makes a signal that aborts by itself after some milliseconds, with a TimeoutError (DOM). So a component can give one fetch() its own signal and a time limit (timeout and any):
const leaving = new AbortController();
const signal = AbortSignal.any([leaving.signal, AbortSignal.timeout(5000)]);
console.log(signal.aborted);
leaving.abort();
console.log(signal.aborted, signal.reason.name);- Line 2 joins the component's signal with a 5-second limit.
- Line 4 aborts the component's signal.
It prints false, then true AbortError. The joined signal took the reason of the signal that aborted. Both work in every major browser:
Why does moving an element fetch its data again?
A list that's sorted moves its rows. append(), prepend(), and insertBefore() take an element off the page and put it back (lesson 18.3). So it gets disconnectedCallback(), then connectedCallback(). A component that aborts when it leaves and asks when it joins throws away its request on every move. Press Move matcha to the top:
<div id="shelf"> <tea-notes tea-id="sencha"></tea-notes> <tea-notes tea-id="oolong"></tea-notes> <tea-notes tea-id="matcha"></tea-notes></div><button id="move">Move matcha to the top</button><script type="module"> import "./kitchen.js"; import "./tea-notes.js"; const shelf = document.querySelector("#shelf"); document.querySelector("#move").addEventListener("click", () => { shelf.prepend(shelf.lastElementChild); });</script>prepend() takes matcha off the page and puts it back at the top. disconnectedCallback() aborts its request, and connectedCallback() starts a new one. The kitchen makes matcha twice.
- Lines 2 to 4 are three notes. Line 12 moves the last one, matcha, to the top.
- In the first tea-notes.js, line 9 asks when the notes connect, and line 13 aborts when they leave.
Each choice prints Asked for sencha, Asked for oolong, and Asked for matcha as it loads. With prepend(), Move prints The kitchen stopped matcha, then Asked for matcha: the same tea, ordered twice. With the microtask choice, nothing more is printed. With moveBefore(), it prints Moved matcha: its request goes on.
prepend() takes matcha off the page and puts it back, so both callbacks run: the request is aborted and asked for again. moveBefore() runs only connectedMoveCallback(), and the request goes on.Ravi orders a Matcha, then moves to a seat by the window. A careless waiter sees the empty seat, cancels the order, and takes a new one at the window. A careful waiter waits a moment to see where Ravi sits. Better still, Ravi says, "I'm only moving."
- In real life: Ravi getting up
- In JavaScript: disconnectedCallback()
- In real life: Ravi sitting down by the window
- In JavaScript: connectedCallback()
- In real life: Waiting a moment before cancelling
- In JavaScript: Cleaning up a microtask later
- In real life: Ravi saying, I'm only moving
- In JavaScript: moveBefore() calling connectedMoveCallback()
Wait a microtask before you clean up
Nolan Lawson's fix: in disconnectedCallback(), wait one microtask, then check isConnected (Nolan Lawson). A microtask is a small job the browser runs as soon as the current code ends (microtasks). A move puts the element back before that, so the check sees it on the page. The second choice's tea-notes.js does this:
- Line 14 waits a microtask. Line 15 stops if the notes are back. Lines 16 and 17 clean up only for a real removal.
- Line 5 stops
connectedCallback()from asking again while a request is open.
He found that Solid, Svelte, and Vue wait the same way when they build custom elements. So does the kit's timer (lesson 3.5), and Lit's SignalWatcher (lesson 18.5).
Tell the browser it's only a move
moveBefore() moves an element without taking it off the page. With a connectedMoveCallback() in the class, the browser calls only that (lesson 3.5). In the third choice, lines 16 to 18 of tea-notes.js print the move, and nothing is aborted. Chrome and Firefox have it, and Safari doesn't yet. So a component that fetches should wait a microtask as well.
How do you build a task controller?
Look back at what the notes needed by hand: a status, a value, an error, a controller, a guard against old answers, and a careful disconnectedCallback(). Every component that loads data needs the same. A task controller packs it into one object.
A controller adds itself to its host, and the host calls its hooks (lesson 19.3). The kit's new task.js holds TeaTask, which uses two hooks. Lit has the same idea in @lit/task (Lit). First, what it keeps:
export class TeaTask {
status = "initial";
value = undefined;
error = undefined;
#args;
#controller;
#run = 0;
constructor(host, { task, args }) {
Object.assign(this, { host, task, args });
host.addController(this);
}- Lines 2 to 4 are what the host reads: the status, the value, and the error.
- Lines 5 to 7 are private: the last arguments, the controller, and a run counter.
- Lines 9 to 12 keep the task function and the args function, and add the task to its host.
hostUpdate() {
const args = this.args();
const same = this.#args?.length === args.length && args.every((arg, i) => Object.is(arg, this.#args[i]));
if (!same) this.run(args);
}
hostDisconnected() {
queueMicrotask(() => {
if (this.host.isConnected || this.status !== "pending") return;
this.#run++;
this.#args = undefined;
this.#controller.abort();
});
}- Lines 1 to 5: before each update,
hostUpdate()reads the arguments. Line 3 compares them, one by one, withObject.is. Line 4 runs the task only when one changed. - Lines 7 to 14: when the host leaves, line 8 waits a microtask. Line 9 stops if the host is back, or if nothing is loading. Lines 10 to 12 forget the run and its arguments, and abort it.
Line 11 matters. With the arguments forgotten, the task runs again if the host comes back. Without it, the notes would stay at Loading forever.
async run(args = this.args()) {
this.#args = args;
if (this.status === "pending") this.#controller.abort();
const controller = (this.#controller = new AbortController());
const run = ++this.#run;
this.status = "pending";
this.host.requestUpdate();
try {
const value = await this.task(args, { signal: controller.signal });
if (run !== this.#run) return;
[this.status, this.value, this.error] = ["complete", value, undefined];
} catch (error) {
if (run !== this.#run) return;
[this.status, this.value, this.error] = ["error", undefined, error];
}
this.host.requestUpdate();
}- Line 3 aborts the run before this one, if it's still pending.
- Line 4 gives this run its own controller. Line 5 gives it a number.
- Lines 6 and 7 set the status to pending, and ask for an update.
- Line 9 calls the task function with the arguments and the signal.
- Lines 10 and 13 return if a newer run has started. An old answer can't touch the status.
- Lines 11 and 14 keep the value or the error. Line 16 asks for the update that draws it.
tea-id changes, run 2 aborts run 1, and run 1's answer is ignored if it still comes. Only the newest run sets the status.At Leaf and Kettle, every order gets a numbered ticket on the kitchen rail. When a table changes its order, the old ticket comes down and a new one goes up. If the old tea was already brewing, the server checks the number and doesn't bring it.
- In real life: The numbered ticket on the rail
- In JavaScript: The run number, ++this.#run
- In real life: Taking the old ticket down
- In JavaScript: Aborting the run before
- In real life: Checking the number before serving
- In JavaScript: run !== this.#run
- In real life: The ticket's mark: waiting, ready, or sold out
- In JavaScript: status
render({ initial, pending, complete, error }) {
if (this.status === "pending") return pending?.();
if (this.status === "complete") return complete?.(this.value);
if (this.status === "error") return error?.(this.error);
return initial?.();
}
}Lines 1 to 5 call the function for the status, like the object of functions in the states file. Here is the kit's new tea-notes, built on it:
import { TeaElement } from "./element.js";
import { TeaTask } from "./task.js";
export class TeaNotes extends TeaElement {
static attributes = { teaId: { reflect: true } };
static styles = [":host { display: block; }"];
static template = `<p part="status" role="status"></p><button type="button" hidden>Try again</button>`;
#notes = new TeaTask(this, {
task: async ([teaId], { signal }) => {
const response = await fetch(`/api/teas/${teaId}`, { signal });
if (!response.ok) throw new Error(`The kitchen answered ${response.status}.`);
return response.json();
},
args: () => [this.teaId],
});
constructor() {
super();
this.renderRoot.querySelector("button").addEventListener("click", () => this.#notes.run());
}
connectedMoveCallback() {}
render() {
this.renderRoot.querySelector("p").textContent = this.#notes.render({
pending: () => `Loading ${this.teaId}`,
complete: (tea) => `${tea.name}: ${tea.notes}`,
error: (error) => `Could not load ${this.teaId}. ${error.message}`,
});
this.renderRoot.querySelector("button").hidden = this.#notes.status !== "error";
}
}
customElements.define("tea-notes", TeaNotes);- Lines 8 to 15 make the task. Line 10 hands the signal to
fetch(). Line 14 is the args function: the tea-id. - Line 19: Try again runs the task again.
- Line 22 is an empty
connectedMoveCallback(), somoveBefore()keeps the request. - Lines 25 to 29 draw the status line. Line 30 shows Try again only on an error.
Press Switch to oolong, then Answer oolong. Run it again and press Remove the notes. Then try Fail sencha and Try again:
<tea-notes tea-id="sencha"></tea-notes><button id="switch">Switch to oolong</button><button id="remove">Remove the notes</button><script type="module"> import "./kitchen.js"; import "./tea-kit/index.js"; const notes = document.querySelector("tea-notes"); document.querySelector("#switch").addEventListener("click", () => (notes.teaId = "oolong")); document.querySelector("#remove").addEventListener("click", () => notes.remove());</script>- Line 6 loads the kit, with its new tea-notes.
- Line 8 sets
teaId, the property for the tea-id attribute. Line 9 removes the notes.
Switch prints The kitchen stopped sencha, and Answer oolong shows Oolong: toasty, like honey. Remove prints The kitchen stopped sencha, a microtask later. Try again shows Loading sencha, with a new order on the board. The component says what to load and how to draw it. The task does the rest.
How does Lit's Task compare?
@lit/task's Task does the same job. Its docs list what it handles: it reads its arguments when the host updates, runs when they change, tracks the status, keeps the last value or error, and lets only the newest run complete the task (Lit). Its source shows the same steps as TeaTask:
hostUpdate()runs the task when the arguments change (lines 259 to 263, and 291 to 302);run()aborts a pending run before it starts a new one (lines 321 and 322);- each run gets a number, and only the newest one changes the status (line 344 and line 354).
TeaElement is a controller host, so Lit's Task runs on it too. Press Switch to oolong, then Remove the notes:
<tea-notes tea-id="sencha"></tea-notes><button id="switch">Switch to oolong</button><button id="remove">Remove the notes</button><script type="module"> import "./kitchen.js"; import "./tea-notes.js"; const notes = document.querySelector("tea-notes"); document.querySelector("#switch").addEventListener("click", () => (notes.teaId = "oolong")); document.querySelector("#remove").addEventListener("click", () => notes.remove());</script>Switch to oolong aborts sencha's request. Remove the notes aborts oolong's a microtask later, because the notes are still off the page.
Both print The kitchen stopped sencha on Switch. Only TeaTask prints The kitchen stopped oolong on Remove. Lit's Task has hostUpdate() and hostUpdated(), and no hostDisconnected() (lines 259 to 269). With Lit, abort it yourself in disconnectedCallback(), with its abort() (lines 401 to 405). Its statuses are numbers in TaskStatus (lines 25 to 30). Read each row across:
| Question | The kit's TeaTask | @lit/task's Task |
|---|---|---|
| What are its statuses? | Four strings: initial, pending, complete, and error. | Four numbers in TaskStatus: INITIAL is 0, PENDING 1, COMPLETE 2, and ERROR 3. |
| When does it run? | In hostUpdate(), when an argument has changed. | In hostUpdate() too, by default. autoRun can make it run after the update instead, or only when you call run(). |
| What happens to an older run? | Its signal is aborted, and its answer is ignored. | The same. Its signal is aborted, and only the newest call completes the task. |
| What happens when the host leaves the page? | A microtask later, if the host is still off the page, the run that's going on is aborted. | Nothing. It has no hostDisconnected(). Call its abort() in disconnectedCallback() yourself. |
| What else does it have? | Nothing more. Without its comments, it's 53 lines. | taskComplete, a promise for the run; onComplete and onError; initialValue; argsEqual; and abort(). |
What does GitHub's include-fragment-element do?
GitHub's include-fragment element loads HTML from its src. It's small, and it makes different choices:
- It loads in
connectedCallback()(lines 100 to 102), and again whensrcchanges (lines 79 to 91). - It doesn't abort. A second load while one is running is skipped (line 160).
- It fires loadstart, load, error, and loadend, in the order an image does (lines 231 to 233).
- Its
fetch()is a method (lines 127 to 129). A page or a test can replace it, the way kitchen.js replaces the browser's.
That last idea is close to the dependency injection of lesson 19.4: someone else can hand the component the fetch() it uses.
Adding a task controller to the tea kit
This version of the kit is kitAfter195. Two files are new, and one changes:
- tea-kit/task.js, new:
TeaTask. - tea-kit/tea-notes.js, new: the notes, last in index.js.
- tea-kit/custom-elements.json: the two new modules.
Here the kit's notes sit on a shelf. Press Answer sencha and Fail oolong. Then press Move matcha to the top, and Answer matcha:
<div id="shelf"> <tea-notes tea-id="sencha"></tea-notes> <tea-notes tea-id="oolong"></tea-notes> <tea-notes tea-id="matcha"></tea-notes></div><button id="move">Move matcha to the top</button><script type="module"> import "./kitchen.js"; import "./tea-kit/index.js"; const shelf = document.querySelector("#shelf"); document.querySelector("#move").addEventListener("click", () => { const matcha = shelf.lastElementChild; if ("moveBefore" in shelf) shelf.moveBefore(matcha, shelf.firstElementChild); else shelf.prepend(matcha); });</script>- Line 13 moves matcha with
moveBefore()where the browser has it. Line 14 usesprepend()where it doesn't.
The shelf shows Matcha: rich and creamy, Sencha: grassy and sweet, and Could not load oolong. The kitchen answered 500. Matcha's one order lived through the move. With moveBefore(), its connectedMoveCallback() keeps it. With prepend(), its task's microtask wait does.
When should a component abort? Sort each moment:
- The tea-id changes while the notes load
- The notes are removed from the page for good
- A list moves the notes with moveBefore(), and their class has connectedMoveCallback()
- A list moves the notes with append(), and cleanup waits a microtask
- The kitchen answers with status 500
- The network is down, and fetch() rejects with a TypeError
Sort each moment by what the notes should do with their request.
Common mix-ups
- "The browser waits for an async connectedCallback()." No. It ignores the promise.
prepend() returnedprinted before the notes came. - "Removing an element stops its async code." No. The rest still ran, and printed
On the page: false. - "Answers come back in the order you asked." No. Sencha's old answer came last, and covered Oolong.
- "fetch() rejects on a 404 or a 500." No. It resolves, with
response.okfalse. Throw it yourself. - "abort() stops the work by itself." No. A signal is only a signal. Hand it to
fetch(), or check it, as Lit's docs say. - "An aborted request is an error to show." No. You aborted it. Return quietly when the name is AbortError.
- "Check the AbortError's message." No. Each browser words it its own way. Check
error.name. - "Sorting a list leaves its elements alone." No.
prepend()ran both callbacks, and matcha was ordered twice. - "Lit's Task stops when its element leaves the page." No. It has no
hostDisconnected(). Call itsabort()yourself.
Practice exercises
Predict the three lines, in order, then run it.
<script type="module"> class TeaGreeting extends HTMLElement { async connectedCallback() { console.log("connectedCallback starts"); const response = await fetch("data:text/plain,Sencha"); console.log(`The answer: ${await response.text()}`); } } customElements.define("tea-greeting", TeaGreeting); document.body.append(document.createElement("tea-greeting")); console.log("append() returned");</script><script type="module"> class TeaGreeting extends HTMLElement { async connectedCallback() { console.log("connectedCallback starts"); const response = await fetch("data:text/plain,Sencha"); console.log(`The answer: ${await response.text()}`); } } customElements.define("tea-greeting", TeaGreeting); document.body.append(document.createElement("tea-greeting")); console.log("append() returned");</script>It prints connectedCallback starts, append() returned, and The answer: Sencha. append() runs the callback, which stops at its await. The browser ignores the promise, so append() returns, and the answer comes after.
Press Switch to oolong, then Answer oolong, then Answer sencha. What do the notes show at the end?
<tea-notes tea-id="sencha"></tea-notes><button id="switch">Switch to oolong</button><script type="module"> import "./kitchen.js"; import "./tea-notes.js"; document.querySelector("#switch").addEventListener("click", () => { document.querySelector("tea-notes").setAttribute("tea-id", "oolong"); });</script><tea-notes tea-id="sencha"></tea-notes><button id="switch">Switch to oolong</button><script type="module"> import "./kitchen.js"; import "./tea-notes.js"; document.querySelector("#switch").addEventListener("click", () => { document.querySelector("tea-notes").setAttribute("tea-id", "oolong"); });</script>The notes show Sencha: grassy and sweet. Oolong's answer drew first, then sencha's old answer drew over it. Nothing compared the answer with the tea-id.
Press Switch to oolong. The notes say Could not load sencha. AbortError, though nothing failed. Fix the tea-notes.js tab. What do the notes show right after Switch then?
<tea-notes tea-id="sencha"></tea-notes><button id="switch">Switch to oolong</button><button id="remove">Remove the notes</button><script type="module"> import "./kitchen.js"; import "./tea-notes.js"; const notes = document.querySelector("tea-notes"); document.querySelector("#switch").addEventListener("click", () => notes.setAttribute("tea-id", "oolong")); document.querySelector("#remove").addEventListener("click", () => notes.remove());</script><tea-notes tea-id="sencha"></tea-notes><button id="switch">Switch to oolong</button><button id="remove">Remove the notes</button><script type="module"> import "./kitchen.js"; import "./tea-notes.js"; const notes = document.querySelector("tea-notes"); document.querySelector("#switch").addEventListener("click", () => notes.setAttribute("tea-id", "oolong")); document.querySelector("#remove").addEventListener("click", () => notes.remove());</script>Only the tea-notes.js tab changes: one line at the top of the catch returns when error.name is AbortError. Before, the abort rejected sencha's fetch(), and the catch drew Could not load sencha. AbortError over Loading oolong. Now the notes show Loading oolong.
Press Switch to oolong. The kitchen still lists sencha, and answering it shows the wrong tea. Fix the tea-notes.js tab. What does the console print when you press Switch then?
<tea-notes tea-id="sencha"></tea-notes><button id="switch">Switch to oolong</button><button id="remove">Remove the notes</button><script type="module"> import "./kitchen.js"; import "./tea-notes.js"; const notes = document.querySelector("tea-notes"); document.querySelector("#switch").addEventListener("click", () => notes.setAttribute("tea-id", "oolong")); document.querySelector("#remove").addEventListener("click", () => notes.remove());</script><tea-notes tea-id="sencha"></tea-notes><button id="switch">Switch to oolong</button><button id="remove">Remove the notes</button><script type="module"> import "./kitchen.js"; import "./tea-notes.js"; const notes = document.querySelector("tea-notes"); document.querySelector("#switch").addEventListener("click", () => notes.setAttribute("tea-id", "oolong")); document.querySelector("#remove").addEventListener("click", () => notes.remove());</script>Only line 11 of the tea-notes.js tab changes: fetch() gets { signal }. Before, the abort had nothing to stop, so sencha stayed on the board, and answering it showed the wrong tea. Now Switch prints The kitchen stopped sencha.
Press Move matcha to the top. The kitchen stops matcha and gets asked again. Fix the tea-notes.js tab so the move keeps the request. How many Asked for lines does the console show in all, after you press Move?
<div id="shelf"> <tea-notes tea-id="sencha"></tea-notes> <tea-notes tea-id="oolong"></tea-notes> <tea-notes tea-id="matcha"></tea-notes></div><button id="move">Move matcha to the top</button><script type="module"> import "./kitchen.js"; import "./tea-notes.js"; const shelf = document.querySelector("#shelf"); document.querySelector("#move").addEventListener("click", () => { shelf.prepend(shelf.lastElementChild); });</script><div id="shelf"> <tea-notes tea-id="sencha"></tea-notes> <tea-notes tea-id="oolong"></tea-notes> <tea-notes tea-id="matcha"></tea-notes></div><button id="move">Move matcha to the top</button><script type="module"> import "./kitchen.js"; import "./tea-notes.js"; const shelf = document.querySelector("#shelf"); document.querySelector("#move").addEventListener("click", () => { shelf.prepend(shelf.lastElementChild); });</script>Only the tea-notes.js tab changes. disconnectedCallback() waits a microtask and cleans up only if the notes are still off the page. connectedCallback() returns while a request is open. The move no longer aborts or asks again, so the console shows the 3 Asked for lines from the start, and no more.
This search never aborts. Type oolong, and the kitchen has six open orders. Rebuild the tea-finder.js tab on the kit's TeaTask. How many requests does the kitchen stop when you type oolong?
<tea-finder></tea-finder><script type="module"> import "./kitchen.js"; import "./tea-finder.js";</script><tea-finder></tea-finder><script type="module"> import "./kitchen.js"; import "./tea-finder.js";</script>Only the tea-finder.js tab changes: it's built on TeaElement and TeaTask. Each letter sets query, the next update sees a new argument, and run() aborts the request before. Typing oolong stops o, oo, ool, oolo, and oolon: 5 requests. The empty query returns [] without asking, so nothing is stopped for it.
Check your understanding
Question 1 of 7What does the browser do with the promise an async
connectedCallback()returns?Choose an answer to see the explanation.
Question 2 of 7Notes with no check are removed while their
fetch()waits. What happens when the answer comes?Choose an answer to see the explanation.
Question 3 of 7With this tea-notes, you press Switch to oolong, then Answer oolong, then Answer sencha. What does the console print?
Read the code, then predictclass TeaNotes extends HTMLElement { static observedAttributes = ["tea-id"]; async attributeChangedCallback(name, oldValue, id) { this.textContent = `Loading ${id}`; const tea = await fetch(`/api/teas/${id}`).then((response) => response.json()); if (id !== this.getAttribute("tea-id")) { console.log(`Ignored the old answer for ${id}`); return; } this.textContent = `${tea.name}: ${tea.notes}`; console.log(`Showing ${tea.name}`); } } customElements.define("tea-notes", TeaNotes);Choose an answer to see the explanation.
Question 4 of 7Which check tells an aborted request apart from a real failure?
Choose an answer to see the explanation.
Question 5 of 7A list moves a card with
prepend(). The card asks inconnectedCallback()and aborts indisconnectedCallback(). What happens to its request?Choose an answer to see the explanation.
Question 6 of 7A task function that ignores its signal asked for sencha. A second run then asked for oolong. Now sencha's answer arrives. What does TeaTask do with it?
Choose an answer to see the explanation.
Question 7 of 7What does
@lit/task's Task do when its host leaves the page?Choose an answer to see the explanation.
Key takeaways
- Start a request in connectedCallback(). The browser ignores the promise an async one returns.
- Code after an await can run on a removed element. Check isConnected, or use a signal.
- Keep one status, pending, complete, or error, and draw from it. Throw when response.ok is false.
- Answers can come back out of order. Ignore old ones, or better, abort them.
- Abort on new input and when the element leaves. Check error.name for AbortError, never the message.
- A move with append() runs both callbacks. Wait a microtask before cleaning up, and use moveBefore() where it exists.
- A task controller keeps the status, value, and error, aborts old runs, and keeps only the newest answer.
- @lit/task's Task does the same, but doesn't abort when its host leaves the page.
- Module 19 built a toolkit: TeaElement (19.1), declared attributes (19.2), mixins and controllers (19.3), context (19.4), and tasks (19.5). Lit and its packages cover the same ground, and the next stage starts with Lit.
Remember the one-liner.
Ask when you join, draw from a status, and abort what's stale.
Sources
The facts on this page come from these docs, specifications, posts, and source files:
- Async Tasks, Lit.
- Using custom elements: lifecycle callbacks, MDN.
- Node: isConnected, MDN.
- Is it okay to make connectedCallback async?, Nolan Lawson.
- Response: ok, MDN.
- AbortController, MDN.
- AbortSignal: throwIfAborted(), MDN.
- Aborting ongoing activities, DOM Standard.
- Creating and throwing exceptions, Web IDL Standard.
- Using Cancellation Signals, WebComponents.Guide.
- AbortSignal: any(), MDN.
- AbortSignal: timeout(), MDN.
- Avoiding unnecessary cleanup work in disconnectedCallback, Nolan Lawson.
- Element: moveBefore(), MDN.
- task.ts, at @lit/task 1.0.3, Lit.
- include-fragment-element.ts, at v6.4.1, GitHub.
- browser-compat-data, MDN.
- web-features, W3C WebDX Community Group.
Support data comes from MDN's browser-compat-data and the W3C WebDX Community Group's web-features.
Coming next: Why Lit?, the first lesson of the Lit stage. Lit adds reactive properties and fast templates to standard custom elements, and you build a first Lit component.