Skip to Content
Effetch Query

Introduction

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.

Release candidate

The API is frozen for 0.1.0: the 0.1.0-rc.N releases fix bugs and only ever add to it. With Effetch, it needs Effetch 0.1.0-rc.4 or later in 0.1. The release notes say when a release raises that.

Why Effetch Query

Effetch Query started in real frontend projects built with Effect and Effetch. Their API calls were Effects, with typed errors, services and retries. Their UI used TanStack Query, the standard way to cache server data in React. Joining the two meant writing a bridge: run each Effect into a promise, hand the promise to TanStack Query, and turn its errors back into something the UI could match on.

That bridge was where the trouble lived. Past the promise, errors lost their Effect types, a query couldn't use the app's layers (the values that build its services), and stopping an Effect that was no longer needed took wiring of its own. Effetch had made each call effectful; what was still missing was a cache built on Effect.

Effetch Query is that cache. Instead of patching TanStack Query, it brings the parts of it that make apps feel fast into Effect itself: one fetch shared by every component, fresh data in the background, optimistic updates and invalidation by key.

With thanks to TanStack Query. Effetch Query owes its model, its vocabulary and many of its defaults to TanStack Query. If you know it, you'll feel at home here, and Coming from TanStack Query maps one to the other. TanStack Query is the industry standard for data fetching, and the right choice for most apps. Effetch Query is an alternative for people building their apps with Effect, who want their server state to be Effect as well.

Want to keep TanStack Query and still write your frontend with Effect? Watch tanstack-effect-bridge, our next project.

How it works

Seven ideas carry the whole library.

A query is an Effect with a key

You describe how to load something, such as GET /todos/1, and give it a key, such as ["todos", 1]. The key is how the cache finds the value again, and how you refer to it later, say to refetch every query under ["todos"]. With Effetch, an endpoint's route gives you the key, so you rarely write one.

The query client holds the cache

Queries hold no data themselves. Values live in a query client, which runs queries with your app's services and keeps what they return. A browser app has one client; a server makes one per request.

Values are fresh, then stale

A value counts as fresh for the query's staleTime after it's fetched, and stale after that. A stale value is still shown, and refetched in the background when a component starts using the query, when the app comes back into focus or back online, or when you say it's out of date. A query that nothing uses keeps its value for its gcTime, then lets it go.

A result says where a query is

Reading a query gives an AsyncResult from Effect:

  • Initial, before there's a value;
  • Success, with the value;
  • Failure, with the full Cause, so you can tell a 404 from a network error from a bug.

Each also has a waiting flag, true while a fetch is in progress. A background refetch shows the old value with waiting: true, so a component can keep showing it and add a spinner.

A mutation changes data, and says what's out of date

A mutation runs an Effect that changes something on the server, such as toggling a todo. When it succeeds, it invalidates the queries it names, and the ones on screen refetch. It can also write to the cache straight away, an optimistic update, and that write is undone if the mutation fails.

Your services are typed

You tell Effetch Query once which services your app provides, such as your API client. Queries and mutations can use them, a query that needs anything else doesn't compile, and a client made without a layer that provides them doesn't compile either.

One cache, everywhere

React only subscribes to all of this: the cache is built on Effect's own reactivity (effect/reactivity atoms), so the same queries work in components, in route loaders, on the server, and in plain Effect code.

At a glance

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  from "effect/http/FetchHttpClient";
import * as  from "effect/Layer";
import * as  from "effect/reactivity/AsyncResult";
import * as  from "effect/Schema";

import {  } from "@monarcode/effetch";
import {  } from "@monarcode/effetch-query";
import {  } from "@monarcode/effetch-query/effetch";
import {
  ,
  ,
  ,
} from "@monarcode/effetch-query/react";

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

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

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

const  = ();

// A cached query for each call of the endpoint.
const  = .(
  .("GET /todos", { : .() }),
  { : "1 minute" },
);

// A mutation that refetches the todos once it succeeds.
const  = .(
  .("PATCH /todos/:id", {
    : .({ : . }),
    : ,
  }),
  { : [] },
);

// The cache, which runs queries with your services.
const  = .({
  : ..(.(.)),
});

export function () {
  return (
    < ={}>
      < />
    </>
  );
}

function () {
  const  = (());
  const  = ();

  return .(, {
    : () => <>Loading…</>,
    : () => <>Couldn't load your todos.</>,
    : ({  }) => (
      <>
        {.(() => (
          < ={.}>
            <
              ={() =>
                void .({
                  : { : . },
                  : { : !. },
                })
              }
            >
              {. ? "✓" : "○"} {.}
            </>
          </>
        ))}
      </>
    ),
  });
}

What's next

On this page