Getting started
Build a small todo app: an Effetch client, a query client, two queries, a component and a mutation.
This tutorial walks you through a small todo app: an Effetch client, a query client, two queries, a component that shows them, and a mutation that changes them. The other pages build on the same files, so each example names the file it lives in.
Before you begin
Install Effetch Query with Effetch, Effect and React.
1. Describe your API
Start with an Effetch client for your API, declared as a service with
Fetch.Service. 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 : ;
}
}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. 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. Every option the client takes is listed in The client.
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]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.
Without endpoints. You can also call your Effetch client yourself.
Query.make defines one query, and Query.family defines one query per
argument, each from an Effect you write:
import * as from "effect/Schema";
import { } from "@monarcode/effetch-query";
import { , } from "./api.js";
export const = .({
: ["todos", "list"],
: (: { readonly : boolean }) =>
.(() =>
.("/todos", { : , : .() }),
),
});
// todos({ done: false }) is the query keyed ["todos", "list", { done: false }]
export const = .({
: ["todos", "detail"],
: (: number) =>
.(() =>
.("/todos/:id", { : { }, : }),
),
: "1 minute",
});
// todo(1) is the query keyed ["todos", "detail", 1]These work the same as endpoint queries, with the same typed errors. The
difference is what you write yourself: the key, which an endpoint takes
from its route, and a schema for server rendering,
which an endpoint takes from its output.
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.
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 (
< ={}>
< />
</>
);
}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 once 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", {
: .({ : . }),
: ,
}),
{ : [] },
);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"}
</>
);
}Without endpoints. Mutation.make defines a mutation from an Effect
you write. Its variables are whatever its run takes, here the todo to
toggle:
import { } from "@monarcode/effetch-query";
import { , } from "./api.js";
export const = .({
: (: ) =>
.(() =>
.("/todos/:id", {
: { : . },
: { : !. },
: ,
}),
),
// A key reaches every query under it, endpoint or not.
: [["todos"]],
});
// useMutation(toggleTodo).run(todo)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.
- Showing data in React: every way to read a query in a component, with Suspense, selections and paused screens.
- Mutations: invalidation, optimistic updates, entities and activity.
- Working with the cache: reading and writing the cache from Effect and from plain code, and signing 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.
- The client, Testing and the API reference, for everything else.