Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 38 ยท Reactive Properties

Loading Async Data in Lit Components

Load data in Lit components without race conditions: model pending, complete and error states, cancel stale requests with AbortController and see how @lit/task does it.

Almost every real component needs data that arrives later: a user profile, search results, a price. The render method must stay synchronous and fast, so you cannot simply await inside it. Instead you keep the status of the request as reactive state and render something different for each status.

This lesson builds the pattern by hand so you see every moving part, then shows how the official @lit/task package packages the same idea.

The four states of a request

A request is always in exactly one of four states. Draw them before you write code.

stateDiagram-v2
    [*] --> initial
    initial --> pending: start
    pending --> complete: success
    pending --> error: failure
    complete --> pending: input changed
    error --> pending: retry

Every async view needs a plan for all four boxes, not just "complete".

A component that only handles "complete" shows a blank space while loading and a frozen screen on failure. Users read that as broken.

A hand-written loader

The simplest approach: a reactive status property, plus willUpdate to start a request when the input changes.

Loading, success and error

Notice that _status, _data and _error use state: true: they are private, reactive, and have no attribute. Changing any of them schedules a re-render, which is how the "Loading..." text turns into the result.

Setting reactive properties inside willUpdate does not trigger a second update, because the update is already in progress. Setting them after an await does trigger one, which is exactly what we want here.

The race condition you must handle

Suppose user-id changes from 1 to 2 to 3 quickly. Three requests fly. Responses can arrive in any order, so request 1 might finish last and overwrite the newer result. The user then sees data for the wrong id.

Two defenses exist:

  1. Ignore stale results by remembering which request is the latest.
  2. Cancel old requests with an AbortController so the network work stops too.
Ignoring stale responses

Request "a" is the slowest, so without the controller it would finish last and win. With abort(), only the newest request can ever set _result. Aborting also matters in the real world because fetch(url, { signal }) stops downloading.

The official helper: @lit/task

Writing that boilerplate in every component gets tedious, so Lit ships Task, a reactive controller. It tracks the status, the result and the error, and it re-runs when its arguments change. The code below is read-only because it needs a package install in a real project.

JavaScript
import { LitElement, html } from "lit";
import { Task } from "@lit/task";

class UserCard extends LitElement {
  static properties = { userId: {} };

  _userTask = new Task(this, {
    task: async ([userId], { signal }) => {
      const res = await fetch(`/api/users/${userId}`, { signal });
      if (!res.ok) throw new Error(res.statusText);
      return res.json();
    },
    args: () => [this.userId],
  });

  render() {
    return this._userTask.render({
      pending: () => html`<p>Loading...</p>`,
      complete: (user) => html`<p>${user.name}</p>`,
      error: (e) => html`<p>Failed: ${e.message}</p>`,
    });
  }
}

Task gives you the signal for free, re-runs when args() returns something different, and its render() method picks the right branch. Under the hood it is the same pattern you just wrote: a controller calling requestUpdate() whenever the status changes. If you have not met controllers yet, read reactive controllers first.

Practical advice

  • Debounce typing. Wait about 250 ms after the last keystroke before searching, or you will send a request per letter.
  • Keep old data visible while refreshing for lists where flicker hurts; show a subtle spinner instead of replacing the content.
  • Never swallow errors. Show a message and, where it makes sense, a Retry button that calls the loader again.
  • Do not fetch in the constructor. Properties are not set yet. Use willUpdate, updated or connectedCallback depending on whether you need the inputs; see the update lifecycle.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is the status stored in reactive properties?

    Reactive state triggers an update, and render() reads the status to choose between loading, result and error views.
  2. 2. What does the race condition in async loading look like?

    Responses can arrive out of order. Without cancelling or ignoring stale ones, the last to arrive wins, not the newest request.
  3. 3. What does calling abort() on an AbortController do for a fetch?

    An aborted fetch rejects with an AbortError, which your code should recognize and ignore.
  4. 4. Which pair describes @lit/task?

    Task is a reactive controller that wraps the async state machine and provides a render() helper for each state.

Summary

  • A request is always initial, pending, complete or error; render all four.
  • Keep status, data and error in state: true properties.
  • Start loads from willUpdate when the input property changes.
  • Cancel or ignore stale requests so the newest input always wins.
  • @lit/task is the packaged version of this pattern.

Next: Dispatching Custom Events