repos / starfx

a micro-mvc framework for react apps
git clone https://github.com/neurosnap/starfx.git

starfx / examples / vite-react / src
Eric Bower  ·  2025-06-06

api.ts

 1import { createApi, createSchema, mdw, slice } from "starfx";
 2
 3interface User {
 4  id: string;
 5  name: string;
 6}
 7
 8const emptyUser: User = { id: "", name: "" };
 9export const [schema, initialState] = createSchema({
10  users: slice.table({ empty: emptyUser }),
11  cache: slice.table(),
12  loaders: slice.loaders(),
13});
14export type AppState = typeof initialState;
15
16export const api = createApi();
17api.use(mdw.api({ schema }));
18api.use(api.routes());
19api.use(mdw.fetch({ baseUrl: "https://jsonplaceholder.typicode.com" }));
20
21export const fetchUsers = api.get<never, User[]>(
22  "/users",
23  function* (ctx, next) {
24    yield* next();
25
26    if (!ctx.json.ok) {
27      return;
28    }
29
30    const users = ctx.json.value.reduce<Record<string, User>>((acc, user) => {
31      acc[user.id] = user;
32      return acc;
33    }, {});
34
35    yield* schema.update(schema.users.add(users));
36  },
37);