Effetch Query

Cached queries, made of Effect.

Athe valueEtyped errorsRyour services

A query is an Effect with a key. Effetch Query fetches it once for every component that shows it, refreshes it in the background, and keeps its errors and services typed from the request to the component.

Get started
pnpm add @monarcode/effetch-query @monarcode/effetch
// A cached query for each call of the endpoint.
const  = .(
  .("GET /todos", { : .() }),
  { :  },
);
function () {
  const  = (());
  const  = ();
From Introduction, in the docs. Click a todo to run the mutation, or "1 minute" to change it. Hover a name for its type.

Three components, one cache entry

["todos"]
<Todos />fetched it
Simulated, 10× speedkey ["todos"]GET /todos ×1PATCH /todos/:id ×0fresh for 60sreaders 1

Effect all the way to the component.

A query is an Effect, so its value, its errors and the services it needs keep their types from the request to the component that renders them. Pick one to follow it through the code.

Query errorsRead the page
const  = .(
  .("GET /todos/:id", {
    : ,
    : { 404: , 403: [] },
  }),
  { : "1 minute" },
);

// In a loader: a missing todo is no todo.
export const  = (: number) =>
  .(({ : {  } })).(
    .("TodoNotFound", () => .()),
  );

export function ({  }: { readonly : number }) {
  return .((({ : {  } })))
    .(() => <>Loading…</>)
    .("TodoNotFound", () => <>This todo was deleted.</>)
    .("NotYourTodo", () => <>{.}</>)
    .(() => <>Couldn't load it.</>)
    .(() => <>{.}</>)
    .();
}

Change it once. Every copy follows.

An entity says what identifies a todo. The docs’ toggle writes it into every cached query that holds it before the request leaves, and undoes every write if the request fails.

Optimistic updatesRead the page
export const  = .(
  .("PATCH /todos/:id", {
    : .({ : . }),
    : ,
  }),
  {
    // Every cached copy: its own query, and each list, whatever its filter.
    : ({ ,  }) =>
      .(, (.), () => ({
        ...,
        : .,
      })),
    // The server's version replaces the guess.
    : () => .(, ),
    : [],
  },
);
todos()["todos"]
todos({ query: { done: false } })["todos",{"done":false}]
todo({ params: { id: 2 } })["todos",2]

Click a todo in any of the three queries to run the mutation.

Live between fetches.

live applies a stream of changes, here from a WebSocket, to a fetched list. Each change is an upsert or a removal by id, so applying one twice is safe, and a socket that drops subscribes again.

live-todos.tsPush updates into a query
// A change as an update of the list, by id, so applying it twice is safe.
const  =
  (: ) =>
  (: <>): <> => {
    const  = . === "Saved" ? .. : .;
    const  = .(() => . !== );
    return . === "Saved" ? [..., .] : ;
  };

const  = ("wss://api.example.com/todos/changes").(
  .(() => ()),
  .(),
  .(.("5 seconds")),
);

export const  = .(, { : () =>  });

wss://api.example.com/todos/changesopen

  1. Waiting for the socket…
useQuery(liveTodos())3 todos
  • Write the release notes
  • Review the cache PR
  • Book a room for the demo

Runs where Effect runs.

Browsers, React Native (Hermes), Node 20+, Bun and Deno. It pairs with Effetch, the typed HTTP client for Effect, and works with any Effect too.

Build the todo app.

Getting started builds a small todo app one piece at a time, a file for each step.

Get started
pnpm add @monarcode/effetch-query @monarcode/effetch

With thanks to TanStack Query, whose model, vocabulary and many defaults Effetch Query borrows.

  1. 1Describe your APIapi.ts
  2. 2Create the query clientclient.ts
  3. 3Define your queriestodos.ts
  4. 4Show a queryopen-todos.tsx
  5. 5Change datatoggle-todo.ts