Skip to content

About

Effectful queries and mutations for Effect 4, inspired by TanStack Query. Cached, kept fresh, typed end to end, and made to pair with effetch.

Topics

Resources

Stars

7 stars

Watchers

0 watching

Forks

Repository files navigation

Effetch Query: effectful queries and mutations for Effect 4, inspired by TanStack Query

npm CI bundle size types provenance license

React React Native TanStack Router TanStack Start React Router Next.js Effect

Server state for Effect apps, inspired by TanStack Query.

Most of what an app shows comes from a server: a list of todos, a profile, the price of something. Effetch Query loads that data once, shares it between every component that shows it, keeps it fresh in the background, and updates it when you change something.

Everything in it is Effect. A query is an Effect that runs with your app's services, its errors stay typed all the way to the component, and the cache itself is something your Effect programs can read and write. It works in React, React Native and code with no UI at all.

It's the companion to Effetch, the typed HTTP client for Effect: Effetch makes the call, Effetch Query caches it. It works with any Effect too.

Documentation

The guides and the API reference are at effetch-query.monarcode.dev. Start with Getting started, which builds a small todo app one piece at a time.

Install

Install the package with Effetch and Effect:

pnpm add @monarcode/effetch-query @monarcode/effetch effect

For React, add @effect/atom-react and react (19):

pnpm add @effect/atom-react react

Effetch Query needs effect 4.1 or later. With Effetch, it needs Effetch 0.1.0 or later in 0.1. It runs in browsers, React Native (Hermes), Node 20+, Bun and Deno, and its types need TypeScript 5.7 or later. See Installation for the entry points.

An update within 0.1 doesn't break code written for 0.1.0; breaking changes wait for 0.2.0. Versioning lists the one exception, which follows Effect.

Quick start

Here's a whole React app in one file. It lists the todos from an API and toggles one when you click it:

import * as FetchHttpClient from "effect/http/FetchHttpClient";
import * as Layer from "effect/Layer";
import * as AsyncResult from "effect/reactivity/AsyncResult";
import * as Schema from "effect/Schema";

import { Fetch } from "@monarcode/effetch";
import { QueryClient } from "@monarcode/effetch-query";
import { fromClient } from "@monarcode/effetch-query/effetch";
import {
  QueryProvider,
  useMutation,
  useQuery,
} from "@monarcode/effetch-query/react";

const Todo = Schema.Struct({
  id: Schema.Finite,
  title: Schema.String,
  done: Schema.Boolean,
});

// Your Effetch client, as a service.
class ApiClient extends Fetch.Service<ApiClient>()("ApiClient", {
  baseUrl: "https://api.example.com",
}) {}

declare module "@monarcode/effetch-query" {
  interface Register {
    readonly services: ApiClient;
  }
}

const api = fromClient(ApiClient);

// A cached query for each call of the endpoint.
const todos = api.query(
  Fetch.endpoint("GET /todos", { output: Schema.Array(Todo) }),
  { staleTime: "1 minute" },
);

// A mutation that refetches the todos once it succeeds.
const toggleTodo = api.mutation(
  Fetch.endpoint("PATCH /todos/:id", {
    input: Schema.Struct({ done: Schema.Boolean }),
    output: Todo,
  }),
  { invalidates: [todos] },
);

// The cache, which runs queries with your services.
const queryClient = QueryClient.make({
  layer: ApiClient.layer.pipe(Layer.provide(FetchHttpClient.layer)),
});

export function App() {
  return (
    <QueryProvider client={queryClient}>
      <Todos />
    </QueryProvider>
  );
}

function Todos() {
  const result = useQuery(todos());
  const toggle = useMutation(toggleTodo);

  return AsyncResult.match(result, {
    onInitial: () => <p>Loading…</p>,
    onFailure: () => <p>Couldn't load your todos.</p>,
    onSuccess: ({ value }) => (
      <ul>
        {value.map((todo) => (
          <li
            key={todo.id}
            onClick={() =>
              void toggle.run({
                params: { id: todo.id },
                body: { done: !todo.done },
              })
            }
          >
            {todo.done ? "✓" : "○"} {todo.title}
          </li>
        ))}
      </ul>
    ),
  });
}

Guides

Examples

The examples/ folder has complete programs, typechecked with the package. effect-only and the full apps are also tested, in test/examples/. There are five:

  • effect-only.ts: queries, a live query, the cache and mutations from Effect code, with no UI.
  • basic/: the smallest React app, with dummyjson.com's todos and an optimistic toggle.
  • tanstack-start/: a full TanStack Start app on Effetch endpoints: sign-in, a user's todos, a list with "Load more", a streamed detail page and a missing one.
  • tanstack-start-httpclient/: the same app on Effect's HttpClient, without Effetch.
  • react-router/: the same app in React Router's framework mode, on Effetch endpoints.

The examples README walks through each one.

Development

To work on Effetch Query, you need Node 24 and pnpm 10 (corepack enable picks the pinned version). To install the dependencies and run every check, run:

pnpm install
pnpm run check

The package has the following scripts:

Script What it does
pnpm run build Builds dist/ (ESM and .d.ts) with tsc.
pnpm test Runs the tests, the type tests and the examples' tests with Vitest.
pnpm run typecheck Typechecks src, test and each example.
pnpm run lint Lints with oxlint (lint:effect runs the Effect language service).
pnpm run format Formats with oxfmt (format:check only checks).
pnpm run check:docs Checks every public export has a description, @example and @since, and compiles every example in the JSDoc, this README and the docs site's pages.
pnpm run smoke Packs the package, installs it in a fresh project, typechecks and runs consumers, and checks go-to-definition and hovers.
pnpm run check All of these, plus publint and attw. CI runs it on every pull request.
pnpm run docs:reference Writes the docs site's API reference pages from the JSDoc. check:docs fails when they're out of date.
pnpm run docs:snapshot <line> Freezes a release line's docs into the site once the next line has started: for 0.2.0-rc.0, snapshot 0.1.
pnpm run build:site Builds the package, then the docs site in site/, prerendered to site/dist/client.

To work on the docs site, run pnpm run build once, then pnpm --dir site run dev, which serves it at the address it prints. The site's type hovers and type tables read the built package in dist.

The pre-commit hook runs lint and format:check.

License

MIT

About

Effectful queries and mutations for Effect 4, inspired by TanStack Query. Cached, kept fresh, typed end to end, and made to pair with effetch.

Topics

Resources

Stars

7 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages