Guide

Remote data

A cache shared by key with ascua-query. Deduplication, polling, invalidation and optimistic updates in 2.15 kB.

When a resource is not enough

resource loads data for one view. When several views show the same data —the list of users in the table and in a select—, or when saving something has to refresh what is shown somewhere else, you need a shared cache. That is ascua-query:

sh
stil add ascua-query
ts
import { remote } from "ascua-query";

const users = remote({
  key: () => ["users"],
  load: (_key, { signal }) => fetch("/api/users", { signal }).then((r) => r.json()),
});

view`
  <Show when=${() => users()}>
    ${(list) => view`<For each=${list} key=${(u: User) => u.id}
                            render=${(u: User) => view`<li>${u.name}</li>`}/>`}
  </Show>`;

It reads like a resource: users() is the data, users.state() says what it is doing, users.error() holds the failure and users.reload() loads again. The difference is the key: two queries with the same key, anywhere in the application, share data and requests.

The key is reactive

ts
const conversation = signal<string | null>(null);

const messages = remote({
  key: () => (conversation() ? ["messages", conversation()!] : null),
  load: ([, id], { signal }) => api.messages(id, { signal }),
  interval: () => (polling() ? 5_000 : false),
});

Changing conversation loads the new one; null leaves the query idle. The interval can be reactive too, and it only runs while the tab is visible.

To paginate without the table going blank between pages, keepPrevious: true keeps showing the previous page while the new one arrives; placeholder() says when what is shown belongs to the previous key.

Saving and invalidating

ts
import { invalidate, mutation } from "ascua-query";

const create = mutation({
  run: (data: NewUser) => api.createUser(data),
  onSuccess: () => invalidate(["users"]),
});

view`<button disabled=${() => create.pending()} onclick=${() => create.mutate(form())}>Create</button>`;

invalidate(["users"]) expires everything that starts with "users" —also ["users", 4]— and reloads whatever some view is watching. Since onSuccess returns that promise, create.pending() stays true until the list is up to date: the button is not released too early.

mutate() does not reject: if it fails, the error ends up in create.error(). mutateAsync() returns the result and rejects, for use with await.

What depends on this call —a notice, closing the form— goes in the second argument, as in TanStack Query:

ts
create.mutate(form(), {
  onSuccess: (user) => toast.success(`${user.email} created`),
  onError: () => toast.error("Could not create the user"),
});

They run after the mutation's own on… callbacks, and only those of the last call: if another call starts before it finishes, the previous one's callbacks do not run. Without variables, create.mutate(undefined, { … }).

Optimistic updates

ts
const comment = mutation({
  run: (text: string) => api.addComment(id, text),
  onMutate: async (text) => {
    await cancel(["comments", id]);                    // so a stale response does not overwrite this
    const previous = getData<Comment[]>(["comments", id]);
    setData<Comment[]>(["comments", id], (c) => [...(c ?? []), { text, pending: true }]);
    return { previous };
  },
  onError: (_error, _text, ctx) => setData(["comments", id], ctx?.previous),
  onSettled: () => invalidate(["comments", id]),
});

The comment shows up right away. If the server fails, onError puts the cache back as it was; either way, onSettled reloads the truth from the server.

What you don't write by hand

  • Deduplication. While a key is loading, anyone who asks for it waits for that same load.
  • A stale response does not overwrite a new one. Reloading aborts the load in flight and discards its response.
  • A poll that brings the same data repaints nothing. The new data reuses every object that did not change, so a keyed <For> only touches the rows that changed.
  • Retries and reload on return. Three retries with increasing delay, and whatever expired is reloaded when the user comes back to the tab or the network comes back.

The defaults are those of TanStack Query, so that migrating an application does not change how it behaves; configure() changes them for every query and each remote() can change them for its own.

From TanStack Query

The mapping that came out of migrating a real React application (29 hooks):

TanStack Query ascua-query
useQuery({ queryKey, queryFn }) remote({ key: () => [...], load: (key) => … })
enabled: !!id key returns null while there is no id
placeholderData: keepPreviousData keepPrevious: true
refetchInterval: polling ? 5000 : false interval: () => (polling() ? 5000 : false)
refetchOnWindowFocus refetchOnFocus
new QueryClient({ defaultOptions }) configure({ … }), no provider
data, isLoading, isFetching r(), r.state() === "loading", r.loading()
useMutation({ mutationFn }) mutation({ run })
mutate(v, { onSuccess }) the same
qc.invalidateQueries({ queryKey }) invalidate(prefix)
qc.getQueryData / setQueryData / cancelQueries getData / setData / cancel

Two differences in shape:

  • A remote lives as long as its scope. It is created inside the component that uses it, not in a hook called on every render: the component runs once.
  • What changes comes in as a function. A hook receives the filters for this render; here the factory receives how to read them, and the key follows them on its own:
ts
// React: useConversations(filters)
export function conversations(filters: () => Filters) {
  return remote({
    key: () => ["conversations", filters()] as const,
    load: ([, f]) => api.conversations(f),
    keepPrevious: true,
    interval: 15_000,
  });
}

A poll brings new objects every time, and a <For> does not repaint a row whose key did not change: the row reads the data with the second parameter of render.

On the server

remote does not load on the server: it stays idle, because a module cache shared between requests would mix data from different users. The data of a server-rendered page comes from load() in the site kit.