React ​
bash
npm install @flattype/react @flattype/modelstsx
import { FlatProvider, useFlat, useFlatStream, useFlatSuspense } from "@flattype/react";
<FlatProvider baseURL="/api" headers={{ authorization: `Bearer ${token}` }}>
<App />
</FlatProvider>;
function Users() {
const { data, error, loading, refetch } = useFlat("/users", { model: User, list: true });
if (error) return <ErrorMessage error={error} />; // HttpError, ModelError or a network error
if (!data) return <Spinner />;
return <UserList users={data} onRefresh={refetch} />; // data: User[]
}
function Profile({ id }: { id: number }) {
const { data: user } = useFlatSuspense(`/users/${id}`, { model: User }); // inside <Suspense>
return <h2>{user.fullName}</h2>; // user: User, never undefined
}
function Export() {
const { rows, done } = useFlatStream("/export", { model: Row, table: "rows" });
return <Table rows={rows} footer={done ? "Done" : `Loading… ${rows.length}`} />; // rows appear while downloading
}| Hook | Returns | Notes |
|---|---|---|
useFlat(url, options) | { data, error, loading, refetch } | A new URL aborts the old request. Old data stays while the next loads. url: null or enabled: false skips the request |
useFlatSuspense(url, options) | { data, refetch } | Suspends, sends errors to an error boundary, and caches by URL (one request for many components) |
useFlatStream(url, options) | { rows, done, error, restart } | One render per network chunk. table picks one table by path |
useModel(data, Model, { list }) | the mapped value | Memoized. For data from props, stores or sockets |
Works with React 18 and 19, in StrictMode and with any server. A JSON-only API works too. A runnable app with Playwright tests in three browsers is in examples/react-app.