Data access
Components ask a hook for data, and every concern below that lives in exactly one layer.
The problem
Every app eventually grows a pile of fetch calls, each with its own idea of auth, retries and what to do when something fails. Or the frontend talks straight to the database, so the API is whatever the tables happen to be, and business logic drifts into components.
Either way, changing anything means touching every screen. Moving to a different backend, adding a retry policy or fixing an error message becomes a hunt.
What I concluded
Put thin layers between the UI and the data, each with one job, and only let each one talk to the one below it.
component useOrder(id)
│
query hook caching, one per resource
│
options factory query key + fetch, or a mock offline
│
api / service the app's whole API; business rules
│
fetcher / DAO auth, typed errors; the only code that
│ knows URLs or table names
backend
Errors are typed, and the type decides
At the bottom, the fetcher turns every failure into a typed error that says two things: is it worth retrying, and is it worth reporting.
abstract class ApiError extends Error {
abstract readonly toast: string; // what the person sees
abstract readonly transient: boolean; // worth retrying?
readonly report: boolean = true; // worth an alert?
}
Then one shared client sets policy once for the whole app: retry only transient errors, with backoff; toast query errors automatically; never toast a not-found, because that renders as a page.
Shape data once
The service layer is where the layers start paying for themselves. Three tables become one call, column names become a typed object, and “is this order late?” gets decided in one place. Without it, every component that shows an order would work that out again, slightly differently.
Every query ships a mock
The options factory takes a mock alongside the real query. Flip one switch and the whole app runs offline, which makes stories, tests and demos free.
Rules
- Components call hooks, hooks call factories. Nothing calls the fetcher directly.
- Retry only what can recover. A network blip or a 503 is transient. A 403 or a parse error isn’t.
- Expected states aren’t errors. A missing record or a timeout doesn’t page anyone.
- Mocks are deterministic. No current time and no random values in a mock.
- Transforms live in the hook, not the factory, so the cached data stays raw and shareable.
What you get
The swap stays local: moving to a new backend changes the bottom layers, and hooks and components don’t change at all. Policy lives in one place, so a retry rule or an error toast is one edit. And everything the app can do is listed in one discoverable object.
Related: Layers, Access control.