Learn Fate

Build your first tracker

Chapter 1 of 6

Build a screen that counts how many pages you have read. Both buttons should show the same total, no matter which one you click.

Install Fate in a browser-rendered React 19.2+ TypeScript app.

pnpm add react-fate @nkzw/fate

Define the data and the write

Put this in state.ts. The data view describes the record’s shape. The schema gives the record a default and exposes it under the progress request root. The mutation reads the current value from the store before adding one.

import { clientSchema, createClient, dataView, type EntityOf } from 'react-fate';

const progress = dataView<{ id: string; pages: number }>('Progress')({
  id: true,
  pages: true,
});

const schema = clientSchema({
  roots: { progress: { id: 'current', type: 'Progress' } },
  types: {
    Progress: { defaults: (id) => ({ id, pages: 0 }), view: progress },
  },
});

export const createAppClient = () =>
  createClient().registerClientSchema(schema, ({ mutation }) => ({
    'progress.advance': mutation('Progress', {
      resolve: ({ store }) =>
        store.update('Progress', 'current', {
          pages: (store.get('Progress', 'current')?.pages ?? 0) + 1,
        }),
    }),
  }));

type AppClient = ReturnType<typeof createAppClient>;
export type Progress = EntityOf<AppClient, 'Progress'>;

declare module '@nkzw/fate' {
  interface ClientRegistration {
    client: AppClient;
  }
}

The module declaration connects the schema-derived client to Fate’s React hooks. Keep it inside the TypeScript project for this app.

Read the data in React

Use this as your app component. Both panels sit under the same provider and read the same record.

import { Suspense } from 'react';
import { FateClient, useFateClient, useRequest, useView, view } from 'react-fate';
import { createAppClient, type Progress } from './state';

const fate = createAppClient();
const ProgressView = view<Progress>()({ pages: true });

function ProgressPanel({ label }: { label: string }) {
  const client = useFateClient();
  const { progress } = useRequest({ progress: { view: ProgressView } });
  const { pages } = useView(ProgressView, progress);

  return (
    <button type="button" onClick={() => client.mutations.progress.advance()}>
      {label} · {pages} pages
    </button>
  );
}

export default function App() {
  return (
    <FateClient client={fate}>
      <Suspense fallback={<p>Loading progress…</p>}>
        <ProgressPanel label="Shelf" />
        <ProgressPanel label="Reader" />
      </Suspense>
    </FateClient>
  );
}

Try it

Click Shelf twice and Reader once. Both buttons should say 3 pages. Reload and both should say 0 pages. The two panels share in-memory client state. A full reload creates a new client and restores the schema defaults.

Getting started · Client state