Getting started
Build a small todo app: an Effetch client, a query client, two queries, a component and a mutation.
You have a React app and an API that serves todos. In this tutorial, you build a page that lists the open todos and marks one done with a click. On the way, you write an Effetch client, a query client, two queries, a component that shows them and a mutation that changes them. The other pages of these docs build on the same files, so each example names the file it lives in.
Before you begin
You need:
- Effetch Query, Effetch, Effect and React, added as Installation shows;
- a React 19 app written in TypeScript, such as one made from Vite's
react-tstemplate, that renders an element with the IDroot; - an HTTP API that serves todos as
{ id, title, done }: a list atGET /todos, filtered by?done=false, one todo atGET /todos/:id, andPATCH /todos/:idto change one.
Steps 1 and 3 use Effetch, the typed HTTP
client for Effect: Fetch.Service declares a client for one API, and
Fetch.endpoint describes one of its routes.
1. Describe your API
Start with an Effetch client for your API, declared as a service with
Fetch.Service. A service is a value your Effects ask for by name, and a
layer is what builds it. If you already use Effetch, you have this file:
import * as from "effect/http/FetchHttpClient";
import * as from "effect/Layer";
import * as from "effect/Schema";
import { } from "@monarcode/effetch";
export const = .({
: .,
: .,
: .,
});
export type = typeof .;
// What the API sends back when a request fails.
export const = .({ : . });
export class extends .<>()("ApiClient", {
: "https://api.example.com",
: ,
}) {}
// Sends requests with the browser's `fetch`.
export const = ..(
.(.),
);
// The services your queries and mutations can use.
declare module "@monarcode/effetch-query" {
interface Register {
readonly : ;
}
}Replace https://api.example.com with your API's address.
The declare module block at the end is the one piece of setup that's
specific to Effetch Query. It tells the library which services your
queries run with. Write it once, anywhere in your app. From then on:
- a query that uses a service you haven't registered doesn't compile;
- the client must be given a layer that provides every registered service.
With several services, use a union: ApiClient | Analytics.
2. Create the query client
The query client holds the cache: queries hold no data themselves, and the client runs them with your services and keeps what they return. Give it the layer that provides your services, and it builds the layer the first time a query needs it:
import { } from "@monarcode/effetch-query";
import { } from "./api.js";
export const = .({
: ,
: {
// Data counts as fresh for 30 seconds after it's fetched.
: { : "30 seconds" },
},
});One client is enough for a browser app. On a server, you make one per request, as Server rendering shows. The query client explains every option the client takes.
3. Define your queries
fromClient takes your Effetch client and turns its endpoints into
queries. Calling the result with an endpoint's params gives you one
cached query per call:
import * as from "effect/Schema";
import { } from "@monarcode/effetch";
import { } from "@monarcode/effetch-query/effetch";
import { , } from "./api.js";
// Queries and mutations that call your API through ApiClient. Its
// defaultError types their errors.
export const = ();
export const = .("GET /todos", {
: .(),
});
export const = .("GET /todos/:id", { : });
export const = .();
// todos({ query: { done: false } }) is the query keyed ["todos", { done: false }]
export const = .(, { : "1 minute" });
// todo({ params: { id: 1 } }) is the query keyed ["todos", 1]todos and todo are families: each is a function that returns the query
for one call. todos lists todos, and todo loads one. This tutorial
shows the list, and the other guides use todo for a todo's own page.
Define queries at module level, as you do your schemas. A query is only a description: nothing is fetched until something reads it, and the data lives in the client.
To call your API without endpoints, see Queries from any Effect.
4. Show a query
useQuery reads a query in a component. The first time, it fetches. After
that, it shows the cached value, and refetches in the background when the
value is stale:
import * as from "effect/reactivity/AsyncResult";
import { } from "@monarcode/effetch-query/react";
import { } from "./todos.js";
export function () {
const = (({ : { : false } }));
return .(, {
: () => <>Loading…</>,
: () => <>Couldn't load your todos.</>,
: ({ }) => (
<>
{.(() => (
< ={.}>{.}</>
))}
</>
),
});
}AsyncResult.match gives you one branch per state: Initial while the
first fetch is in progress, then Success or Failure. A failure holds
the typed error, so you can show a 404 differently from a network error,
as Query errors shows.
To give your components the client, wrap your app in QueryProvider:
import { } from "@monarcode/effetch-query/react";
import { } from "./client.js";
import { } from "./open-todos.js";
export function () {
return (
< ={}>
< />
</>
);
}Then render App into the page, from your app's entry point:
import { } from "react-dom/client";
import { } from "./App.js";
(.("root")!).(< />);Start your app and open it. The page shows "Loading…", then the titles of
your open todos. Two components that show
todos({ query: { done: false } }) share one fetch and one cached value.
5. Change data
A mutation changes data on the server. Its invalidates option names the
queries that are out of date after it succeeds, and the ones on screen
refetch:
import * as from "effect/Schema";
import { } from "@monarcode/effetch";
import { } from "./api.js";
import { , } from "./todos.js";
export const = .(
.("PATCH /todos/:id", {
: .({ : . }),
: ,
}),
{ : [] },
);[todos] reaches every todo list, whatever its filter, but not todo's
queries: a family matches only its own calls.
Invalidate after a mutation shows how to
reach both.
useMutation runs it from a component. For an endpoint mutation, the
variables you pass to run are the endpoint's call options:
import * as from "effect/reactivity/AsyncResult";
import { } from "@monarcode/effetch-query/react";
import type { } from "./api.js";
import { } from "./toggle-todo.js";
export function ({ }: { readonly : }) {
const { , } = ();
return (
<
={.}
={() =>
void ({ : { : . }, : { : !. } })
}
>
{.()
? "Try again"
: .
? "Undo"
: "Done"}
</>
);
}result.waiting is true while the request is in progress, so the button
can't be clicked twice. If the request fails, the button offers to try
again.
Last, render the button in each row of the list. Here's open-todos.tsx
with it:
import * as from "effect/reactivity/AsyncResult";
import { } from "@monarcode/effetch-query/react";
import { } from "./todos.js";
import { } from "./toggle-button.js";
export function () {
const = (({ : { : false } }));
return .(, {
: () => <>Loading…</>,
: () => <>Couldn't load your todos.</>,
: ({ }) => (
<>
{.(() => (
< ={.}>
{.} < ={} />
</>
))}
</>
),
});
}Click Done beside a todo. The button is disabled while the request runs. When the server answers, the list refetches in the background and the todo leaves it, since it's no longer open.
Where to go next
That's the whole loop: define a query, show it, change the data, and let the cache refetch. The other pages go deeper, in the same order:
- Queries: keys, errors, freshness and placeholders.
- Read a query: every way to read a query in a component, with Suspense, selections and paused screens.
- Mutations: invalidation, optimistic updates and activity.
- The cache: read and write the cache from Effect and from plain code, keep copies of a record in sync, and sign out.
- Infinite queries and Queries from a stream, for lists that load in pages and values a server pushes.
- React Native, Server rendering and Frameworks, for your platform.
- Examples: complete apps to read and run.
- The query client, Testing and the API reference, for everything else.