4 ms·
A nice approach of separating concerns is having the API layer provide its own, already typed hooks and hook-backed primitives such as `useThing()`/`updateThing
by strogonoff 5y ago
A nice approach of separating concerns is having the API layer provide its own, already typed hooks and hook-backed primitives such as `useThing()`/`updateThing()` (or `API.thing.useData()`/`API.thing.update()`, etc.), which under the hood can do whatever necessary (including using shared logic, API-specific access request handling) while providing common primitives for tracking progress, cancellation[0] and other conveniences. With TypeScript, you can ensure those hooks are typed appropriately and don’t require callers to annotate.
Compared to approaches such as `setAsyncState(API.thing.get<ThingState>())`, which do seem clever, the former approach may be a bit more concise, and I’d argue more predictable (if I see a `setState()`, I’d rather not have to do a double take and reason whether or not it actually sets state where it says it would).
[0] The cancellation approach in the example in this article rubs me wrong, because the update request is not (and can’t really be) actually cancelled, so the thing may be updated without GUI state knowing.
- loh 5y agoYou can certainly compose a `useThing` hook (and others) for more encapsulation and functionality specific to said thing. We actually do this elsewhere as necessary, like with the top level `Store` component. For the most part, it depends on the situation and how concise/redundant (or not) you want to be. In many cases it actually ends up being more concise overall to simply compose `setState(readThing(id))` as needed, instead of creating a specific method for every possibility.
- strogonoff 5y agoI prefer to generalize logic at another level of abstraction, but to each their own.