# Getting started (https://effetch-query.pages.dev/docs/getting-started)

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](https://effetch-query.pages.dev/docs/installation) shows;
- a React 19 app written in TypeScript, such as one made from Vite's
  `react-ts` template, that renders an element with the ID `root`;
- an HTTP API that serves todos as `{ id, title, done }`: a list at
  `GET /todos`, filtered by `?done=false`, one todo at `GET /todos/:id`,
  and `PATCH /todos/:id` to change one.

Steps 1 and 3 use [Effetch](https://effetch.pages.dev), 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:

```ts api.ts
import * as FetchHttpClient from "effect/http/FetchHttpClient";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";

import { Fetch } from "@monarcode/effetch";

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

// What the API sends back when a request fails.
export const ApiError = Schema.Struct({ message: Schema.String });

export class ApiClient extends Fetch.Service<ApiClient>()("ApiClient", {
  baseUrl: "https://api.example.com",
  defaultError: ApiError,
}) {}

// Sends requests with the browser's `fetch`.
export const ApiClientLive = ApiClient.layer.pipe(
  Layer.provide(FetchHttpClient.layer),
);

// The services your queries and mutations can use.
declare module "@monarcode/effetch-query" {
  interface Register {
    readonly services: ApiClient;
  }
}
```

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:

```ts client.ts
import { QueryClient } from "@monarcode/effetch-query";

import { ApiClientLive } from "./api.js";

export const queryClient = QueryClient.make({
  layer: ApiClientLive,
  queries: {
    // Data counts as fresh for 30 seconds after it's fetched.
    defaults: { staleTime: "30 seconds" },
  },
});
```

One client is enough for a browser app. On a server, you make one per
request, as [Server rendering](https://effetch-query.pages.dev/docs/server-rendering) shows.
[The query client](https://effetch-query.pages.dev/docs/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:

```ts todos.ts
import * as Schema from "effect/Schema";

import { Fetch } from "@monarcode/effetch";
import { fromClient } from "@monarcode/effetch-query/effetch";

import { ApiClient, Todo } from "./api.js";

// Queries and mutations that call your API through ApiClient. Its
// defaultError types their errors.
export const api = fromClient(ApiClient);

export const listTodos = Fetch.endpoint("GET /todos", {
  output: Schema.Array(Todo),
});
export const getTodo = Fetch.endpoint("GET /todos/:id", { output: Todo });

export const todos = api.query(listTodos);
// todos({ query: { done: false } }) is the query keyed ["todos", { done: false }]

export const todo = api.query(getTodo, { staleTime: "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](https://effetch-query.pages.dev/docs/queries/without-effetch).

## 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:

```tsx open-todos.tsx
import * as AsyncResult from "effect/reactivity/AsyncResult";

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

import { todos } from "./todos.js";

export function OpenTodos() {
  const result = useQuery(todos({ query: { done: false } }));

  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}>{todo.title}</li>
        ))}
      </ul>
    ),
  });
}
```

`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](https://effetch-query.pages.dev/docs/queries/errors) shows.

To give your components the client, wrap your app in `QueryProvider`:

```tsx App.tsx
import { QueryProvider } from "@monarcode/effetch-query/react";

import { queryClient } from "./client.js";
import { OpenTodos } from "./open-todos.js";

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

Then render `App` into the page, from your app's entry point:

```tsx main.tsx
import { createRoot } from "react-dom/client";

import { App } from "./App.js";

createRoot(document.getElementById("root")!).render(<App />);
```

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:

```ts toggle-todo.ts
import * as Schema from "effect/Schema";

import { Fetch } from "@monarcode/effetch";

import { Todo } from "./api.js";
import { api, todos } from "./todos.js";

export const toggleTodo = api.mutation(
  Fetch.endpoint("PATCH /todos/:id", {
    input: Schema.Struct({ done: Schema.Boolean }),
    output: Todo,
  }),
  { invalidates: [todos] },
);
```

`[todos]` reaches every todo list, whatever its filter, but not `todo`'s
queries: a family matches only its own calls.
[Invalidate after a mutation](https://effetch-query.pages.dev/docs/mutations/invalidate) 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:

```tsx toggle-button.tsx
import * as AsyncResult from "effect/reactivity/AsyncResult";

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

import type { Todo } from "./api.js";
import { toggleTodo } from "./toggle-todo.js";

export function ToggleButton({ todo }: { readonly todo: Todo }) {
  const { result, run } = useMutation(toggleTodo);

  return (
    <button
      disabled={result.waiting}
      onClick={() =>
        void run({ params: { id: todo.id }, body: { done: !todo.done } })
      }
    >
      {AsyncResult.isFailure(result)
        ? "Try again"
        : todo.done
          ? "Undo"
          : "Done"}
    </button>
  );
}
```

`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:

```tsx
import * as AsyncResult from "effect/reactivity/AsyncResult";

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

import { todos } from "./todos.js";
import { ToggleButton } from "./toggle-button.js";

export function OpenTodos() {
  const result = useQuery(todos({ query: { done: false } }));

  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}>
            {todo.title} <ToggleButton todo={todo} />
          </li>
        ))}
      </ul>
    ),
  });
}
```

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](https://effetch-query.pages.dev/docs/queries): keys, errors, freshness and placeholders.
- [Read a query](https://effetch-query.pages.dev/docs/react): every way to read a query in a component,
  with Suspense, selections and paused screens.
- [Mutations](https://effetch-query.pages.dev/docs/mutations): invalidation, optimistic updates and
  activity.
- [The cache](https://effetch-query.pages.dev/docs/cache): read and write the cache from Effect and from
  plain code, keep copies of a record in sync, and sign out.
- [Infinite queries](https://effetch-query.pages.dev/docs/queries/infinite) and
  [Queries from a stream](https://effetch-query.pages.dev/docs/queries/streams), for lists that load in
  pages and values a server pushes.
- [React Native](https://effetch-query.pages.dev/docs/react/react-native),
  [Server rendering](https://effetch-query.pages.dev/docs/server-rendering) and
  [Frameworks](https://effetch-query.pages.dev/docs/frameworks), for your platform.
- [Examples](https://effetch-query.pages.dev/docs/examples): complete apps to read and run.
- [The query client](https://effetch-query.pages.dev/docs/client), [Testing](https://effetch-query.pages.dev/docs/testing) and the
  [API reference](https://effetch-query.pages.dev/docs/reference), for everything else.