@bomjan133/react-crud-ui 1.2.5 → 1.2.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,456 +1,456 @@
1
- # Store Factory Guide
2
-
3
- Complete reference for `createCrudStore` (and `createStore`) in @sujanbomjan/react-crud-ui.
4
-
5
- ## Table of Contents
6
- 1. [Overview](#overview)
7
- 2. [Basic Usage](#basic-usage)
8
- 3. [`createStore` is currently broken under ESM](#createstore-is-currently-broken-under-esm)
9
- 4. [Store Options](#store-options)
10
- 5. [Store State](#store-state)
11
- 6. [Store Actions](#store-actions)
12
- 7. [API Request/Response Conventions](#api-requestresponse-conventions)
13
- 8. [Extending with `extraActions`](#extending-with-extraactions)
14
- 9. [Compatibility with `CrudList` / `CrudForm` / `CrudDetail`](#compatibility-with-crudlist--crudform--cruddetail)
15
- 10. [Best Practices](#best-practices)
16
-
17
- Everything below was verified by reading `src/store/createCrudStore.js` in full and running it directly against zustand 5 in Node — not inferred from the function names alone.
18
-
19
- ---
20
-
21
- ## Overview
22
-
23
- `createCrudStore(options)` is a factory that builds a Zustand **state creator** for a single resource, wired to an Axios-compatible `apiClient`. It gives you:
24
-
25
- - Flat list state (`items`, `page`, `pageSize`, `totalItems`, `totalPages`, `search`, `filters`, `sortColumn`, `sortDirection`, `selectedIds`)
26
- - A single-item slot (`item`) for detail/edit views
27
- - `loading` (list operations) and `submitting` (item operations) flags, plus `error`
28
- - CRUD methods: `fetchList`, `fetchOne`, `create`, `update`, `delete`, `bulkDelete`, `replace`
29
- - An `extraActions` escape hatch for anything custom
30
-
31
- **It does not manage form state.** There is no `form.values`/`form.errors`, no `resetForm`/`setFormField`/`initForm` — none of that exists in this factory. If you need form state, either manage it yourself (`useState`/`react-hook-form`) or use `CrudForm`'s **fields mode** (`fields` + `onSubmit`), which is self-contained and doesn't need any of this. See [Compatibility](#compatibility-with-crudlist--crudform--cruddetail) below.
32
-
33
- ---
34
-
35
- ## Basic Usage
36
-
37
- `createCrudStore(options)` does **not** return a ready-to-use hook by itself — it returns a Zustand *state creator function* that still needs zustand's own `create` passed into it. The correct pattern is:
38
-
39
- ```js
40
- // stores/useProductStore.js
41
- import { create } from 'zustand';
42
- import { createCrudStore } from '@sujanbomjan/react-crud-ui';
43
- import apiClient from '@/lib/api'; // an Axios instance
44
-
45
- const useProductStore = createCrudStore({
46
- name: 'products',
47
- apiClient,
48
- endpoint: '/products',
49
- })(create); // <-- note the trailing (create) call
50
-
51
- export default useProductStore;
52
- ```
53
-
54
- Use it like any Zustand store:
55
-
56
- ```jsx
57
- import useProductStore from '@/stores/useProductStore';
58
-
59
- function ProductList() {
60
- const { items, loading, fetchList } = useProductStore();
61
-
62
- useEffect(() => {
63
- fetchList();
64
- }, []);
65
-
66
- return (
67
- <div>
68
- {items.map((product) => (
69
- <div key={product.id}>{product.name}</div>
70
- ))}
71
- </div>
72
- );
73
- }
74
- ```
75
-
76
- ---
77
-
78
- ## `createStore` is currently broken under ESM
79
-
80
- The package also exports a `createStore(options)` "convenience wrapper" that's meant to skip the `(create)` call:
81
-
82
- ```js
83
- export const createStore = (options) => {
84
- const { create } = require("zustand");
85
- return create(createCrudStore(options));
86
- };
87
- ```
88
-
89
- **This throws `ReferenceError: require is not defined` when you `import` the package (ESM)** — verified directly: calling `createStore({...})` after `import { createStore } from '@sujanbomjan/react-crud-ui'` fails immediately, because `require` doesn't exist in an ES module/browser bundle, and the published `dist/index.js` (ESM build) ships this `require("zustand")` call completely un-transformed. It only works if you consume the package's CommonJS build (`require('@sujanbomjan/react-crud-ui')`) directly, since `require` is a real function there.
90
-
91
- **Until this is fixed upstream, don't use `createStore`. Use `createCrudStore(options)(create)` instead** (shown above) — it has no dependency on `require` and works identically in both ESM and CJS.
92
-
93
- ---
94
-
95
- ## Store Options
96
-
97
- | Option | Type | Required | Default | Description |
98
- |--------|------|----------|---------|-------------|
99
- | `apiClient` | Axios instance (or compatible: needs `.get`/`.post`/`.patch`/`.put`/`.delete`) | **Yes** | - | Throws `"createCrudStore: apiClient is required"` if omitted. Not called `api` — see correction below. |
100
- | `endpoint` | `string` | **Yes** | - | Throws `"createCrudStore: endpoint is required"` if omitted. Requests are built as `` `${endpoint}` ``, `` `${endpoint}/` `` (create), and `` `${endpoint}/${id}/` `` (fetchOne/update/delete/replace) — the trailing slashes are hardcoded, matching a Django REST Framework-style API. If your backend doesn't use trailing slashes, use `transformRequest`/a custom `apiClient` interceptor to compensate, or don't rely on this factory's endpoint building. |
101
- | `name` | `string` | No | `"crud"` | Accepted but only used as a label — **not currently used for anything visible** (e.g. no Zustand devtools naming is wired up in this factory). |
102
- | `transformResponse` | `(item) => item` | No | identity | Applied to each item in `fetchList` results and to the single item in `fetchOne`/`create`/`update`/`replace`. **Not called `transformItem`.** |
103
- | `transformRequest` | `(data) => data` | No | identity | Applied to the payload before `create`/`update`/`replace` POST/PATCH/PUT calls. |
104
- | `initialState` | `object` | No | `{}` | Merged into the store's initial state, after the built-in defaults — use this to add custom fields (it does **not** support a nested `filters: {...}` shorthand differently from any other key; it's a plain shallow merge). |
105
- | `extraActions` | `object` | No | `{}` | Merged into the store, after all built-in actions — see [Extending](#extending-with-extraactions). **Not called `extend`, and not a function** — it's a plain object of actions (though you can build that object using `set`/`get` closures yourself before passing it in). |
106
- | `idField` | `string` | No | `"id"` | Field name used to match items in `update`/`delete`/`bulkDelete`/`replace` (e.g. `item[idField] === id`). Set this to `"uuid"` if your API uses UUIDs under that key. |
107
- | `listKey` | `string` | No | `"results"` | Key read from the list response body for the array of items — see [API conventions](#api-requestresponse-conventions). |
108
- | `countKey` | `string` | No | `"count"` | Key read from the list response body for the total item count. |
109
-
110
- > **Corrections vs. an earlier version of this doc:** the real required client option is `apiClient`, not `api`. There is no `transformItem`/`transformList`/`onFetchSuccess`/`onFetchError`/`onCreateSuccess`/`onUpdateSuccess`/`onDeleteSuccess`/`endpoints` (per-action endpoint overrides) option — none of these exist in the source. The only response-shaping hooks are `transformResponse`, `transformRequest`, `listKey`, and `countKey`.
111
-
112
- ---
113
-
114
- ## Store State
115
-
116
- All of this is flat top-level state — there is no nested `pagination`/`form`/`current` object.
117
-
118
- | Field | Type | Initial value | Description |
119
- |-------|------|----------------|-------------|
120
- | `items` | `array` | `[]` | Current page of list results. |
121
- | `item` | `object \| null` | `null` | Currently-loaded single record (populated by `fetchOne`, kept in sync by `update`/`delete`/`replace`). |
122
- | `loading` | `boolean` | `false` | True while `fetchList` or `fetchOne` is in flight. |
123
- | `submitting` | `boolean` | `false` | True while `create`/`update`/`delete`/`bulkDelete`/`replace` is in flight. |
124
- | `error` | `{ message, original, fieldErrors? } \| null` | `null` | Set by any failed request; cleared at the start of the next request, or via `clearError()`. `fieldErrors` (the raw `error.response.data`) is only attached by `create`/`update`/`replace`. |
125
- | `page` | `number` | `1` | Current page. |
126
- | `pageSize` | `number` | `15` | Items per page, sent as the `page_size` query param. |
127
- | `totalItems` | `number` | `0` | Set from the last `fetchList` response. |
128
- | `totalPages` | `number` | `0` | Computed as `Math.ceil(totalItems / pageSize)` after each `fetchList`. |
129
- | `sortColumn` | `string \| null` | `null` | Set via `setSort`. |
130
- | `sortDirection` | `string \| null` | `null` | Set via `setSort`; `"desc"` is sent as a `-` prefix on the `ordering` query param, anything else is sent unprefixed. |
131
- | `search` | `string` | `""` | Set via `setSearch`; sent as the `search` query param. |
132
- | `filters` | `object` | `{}` | Set (replaced wholesale, not merged) via `setFilters`; each key is spread directly into the query params. |
133
- | `selectedIds` | `array` | `[]` | Set via `setSelectedIds`/`clearSelection`; also auto-pruned by `delete`/`bulkDelete`. |
134
-
135
- > **There is no `pagination` object, no `current`/`itemLoading`/`itemError`, and no `form` state.** An earlier version of this doc described a `{ page, totalPages, total, perPage }` pagination object and a full form sub-state (`values`/`errors`/`isDirty`) — none of that exists in `createCrudStore`.
136
-
137
- ---
138
-
139
- ## Store Actions
140
-
141
- ### List actions
142
-
143
- ```js
144
- const {
145
- fetchList, // async (params = {}) => { items, totalItems, totalPages }
146
- setPage, // (page) => void
147
- setPageSize, // (pageSize) => void — also resets page to 1
148
- setSearch, // (search) => void — also resets page to 1
149
- setFilters, // (filters) => void — REPLACES filters wholesale, also resets page to 1
150
- setSort, // (sortColumn, sortDirection) => void
151
- clearError, // () => void
152
- reset, // () => void — resets items/item/loading/submitting/error/page/search/filters/selectedIds/sort
153
- } = useProductStore();
154
-
155
- await fetchList(); // uses current page/pageSize/search/filters/sort
156
- await fetchList({ page: 2 }); // merges extra params into the request (does not update store state)
157
- setFilters({ status: 'active' }); // replaces the whole filters object — see caveat below
158
- ```
159
-
160
- > **`setFilters` replaces, it does not merge.** Calling `setFilters({ status: 'active' })` and later `setFilters({ category: 1 })` leaves `filters` as `{ category: 1 }` — the earlier `status` key is gone. If you need multiple independent filters, merge them yourself: `setFilters({ ...filters, category: 1 })`. There is no `clearFilters()` action — call `setFilters({})` instead.
161
-
162
- ### Selection actions
163
-
164
- ```js
165
- const { selectedIds, setSelectedIds, clearSelection } = useProductStore();
166
-
167
- setSelectedIds([1, 2, 3]);
168
- clearSelection();
169
- ```
170
-
171
- ### Item actions
172
-
173
- ```js
174
- const { fetchOne } = useProductStore();
175
-
176
- const product = await fetchOne(productId);
177
- console.log(product.name);
178
- ```
179
-
180
- > There is no `fetchById` alias, and no `setCurrent`/`clearCurrent` — `item` is only ever set by `fetchOne` (and kept in sync by `update`/`delete`/`replace` when the ids match).
181
-
182
- ### CRUD actions
183
-
184
- ```js
185
- const { create, update, delete: remove, bulkDelete, replace } = useProductStore();
186
-
187
- const newProduct = await create({ name: 'New Product', price: 99.99 });
188
- const updated = await update(productId, { name: 'Updated Name' });
189
- await remove(productId); // the real action is named `delete` — alias it on destructure since `delete` is reserved in some contexts
190
- await bulkDelete([1, 2, 3]); // deletes one-by-one via Promise.all, then updates items/totalItems/selectedIds
191
- const replaced = await replace(productId, fullPayload); // PUT, full replace
192
- ```
193
-
194
- > **The delete method is named `delete`, not `remove`.** Since `delete` is a reserved word in object literal *shorthand* contexts in some older tooling, destructure it with a rename if needed: `const { delete: remove } = useProductStore();`. There is no separate `remove` action.
195
-
196
- All of `create`/`update`/`delete`/`bulkDelete`/`replace` guard against concurrent calls (they no-op while `submitting` is already `true`, except `bulkDelete` which doesn't check `submitting` at all), and all reject (throw) on failure after populating `error`.
197
-
198
- ---
199
-
200
- ## API Request/Response Conventions
201
-
202
- ### `fetchList` request
203
-
204
- ```
205
- GET {endpoint}?page=1&page_size=15&search=foo&ordering=-created_at&<...filters>
206
- ```
207
-
208
- - `page`/`page_size` always sent.
209
- - `search` only sent if non-empty.
210
- - `ordering` only sent if `sortColumn` is set; `sortDirection === 'desc'` prefixes it with `-`.
211
- - Every key in `filters` is spread in directly, then any explicit `params` passed to `fetchList(params)` are spread in last (so they win over store state for that one call, without persisting it back to the store).
212
- - Keys with `undefined` or `''` values are stripped before the request is sent.
213
-
214
- ### `fetchList` response
215
-
216
- Reads, in order of preference:
217
- ```js
218
- const items = data[listKey] || data.data || (Array.isArray(data) ? data : []);
219
- const totalItems = data[countKey] || data.total || items.length;
220
- ```
221
- With the defaults (`listKey: "results"`, `countKey: "count"`), that means:
222
-
223
- ```json
224
- { "results": [ ... ], "count": 42 }
225
- ```
226
-
227
- is read out of the box. A response shaped like `{ "data": [...], "meta": { "total": 42 } }` requires either passing `listKey`/`countKey` (they only look at top-level keys, not nested `meta.total`) or handling reshaping yourself via a response interceptor on `apiClient`, since there is no `transformList` hook.
228
-
229
- ### Single-item requests
230
-
231
- - `fetchOne(id)` → `GET {endpoint}/{id}/`, result passed through `transformResponse`.
232
- - `create(data)` → `POST {endpoint}/`, payload passed through `transformRequest` first, result through `transformResponse`.
233
- - `update(id, data)` → `PATCH {endpoint}/{id}/`.
234
- - `replace(id, data)` → `PUT {endpoint}/{id}/` (full replace).
235
- - `delete(id)` / `bulkDelete(ids)` → `DELETE {endpoint}/{id}/` (one request per id for `bulkDelete`, run concurrently via `Promise.all`).
236
-
237
- ### Error shape
238
-
239
- Every action sets `error` to:
240
- ```js
241
- { message: string, original: Error, fieldErrors?: object }
242
- ```
243
- `message` is resolved from `error.response?.data?.message`, then `.detail`, then `error.message`, then a hardcoded fallback string. `fieldErrors` (the raw `error.response?.data`) is only attached for `create`/`update`/`replace` — useful for mapping server-side validation errors back onto form fields yourself.
244
-
245
- ---
246
-
247
- ## Extending with `extraActions`
248
-
249
- `extraActions` is a plain object merged onto the store after all built-in state/actions — build it with closures over `set`/`get` yourself if it needs to read/write store state:
250
-
251
- ```js
252
- import { create } from 'zustand';
253
- import { createCrudStore } from '@sujanbomjan/react-crud-ui';
254
- import apiClient from '@/lib/api';
255
-
256
- const useProductStoreCreator = (set, get) => ({
257
- archive: async (id) => {
258
- await apiClient.post(`/products/${id}/archive`);
259
- await get().fetchList();
260
- },
261
- duplicate: async (id) => {
262
- const { data } = await apiClient.post(`/products/${id}/duplicate`);
263
- await get().fetchList();
264
- return data;
265
- },
266
- });
267
-
268
- // createCrudStore itself doesn't give you set/get ahead of time, so build
269
- // extraActions inline using zustand's create, or pass simple stateless helpers:
270
- const useProductStore = createCrudStore({
271
- apiClient,
272
- endpoint: '/products',
273
- initialState: { viewMode: 'grid' },
274
- extraActions: {
275
- // Actions defined here only close over module-level values (like apiClient),
276
- // not `set`/`get` — for state-aware extras, patch the store after creation instead:
277
- },
278
- })(create);
279
-
280
- // State-aware extension pattern (recommended): wrap the created hook.
281
- useProductStore.setState((state) => ({
282
- setViewMode: (mode) => useProductStore.setState({ viewMode: mode }),
283
- archive: async (id) => {
284
- await apiClient.post(`/products/${id}/archive`);
285
- await useProductStore.getState().fetchList();
286
- },
287
- }));
288
- ```
289
-
290
- > An earlier version of this doc showed an `extend: (set, get, store) => ({...})` function option — **that option does not exist**. `extraActions` is a plain object, so any action inside it that needs `set`/`get` must either close over the resulting hook itself (as shown above) or be added via `useProductStore.setState(...)` after creation.
291
-
292
- ---
293
-
294
- ## Compatibility with `CrudList` / `CrudForm` / `CrudDetail`
295
-
296
- A store built with `createCrudStore` is **not** a drop-in for every `Q*`/`Crud*` component's `store`/`useStore` prop — each one expects a different shape:
297
-
298
- | Component | What it needs from the store | Compatible with `createCrudStore`? |
299
- |---|---|---|
300
- | `CrudList` (`store` prop) | `items`, `loading`, `error`, `fetchList`, `delete`, `setPage`, `setPageSize`, `setFilters`, `sortColumn`/`sortDirection`/`setSort`, **and a nested `store.pagination` object** (`{ page, pageSize, total, totalPages }`) | **Partially.** `createCrudStore` gives you everything except `pagination` as a nested object — its pagination fields are flat (`page`/`pageSize`/`totalItems`/`totalPages`). Since `CrudList` reads `store?.pagination` directly, it won't find one and will silently fall back to `currentPage`/`pageSize`/`totalItems`/`totalPages` **props** (default `1`/`15`/`0`/`1`) instead of the store's real values — i.e. pagination will look stuck at page 1 unless you bridge it, e.g. `store={{ ...store, pagination: { page: store.page, pageSize: store.pageSize, total: store.totalItems, totalPages: store.totalPages } }}`. |
301
- | `CrudDetail` (`useStore` prop) | `currentItem`, `loading`, `error`, `fetchById` (or `fetchOne`), `delete` | **Partially.** `createCrudStore` has `fetchOne` (used as the fallback) and `delete`, `loading`, `error` — but its single-item field is named `item`, not `currentItem`. `CrudDetail` reads `currentItem` specifically, so you'll need to bridge it too: `useStore={() => { const s = useProductStore(); return { ...s, currentItem: s.item }; }}`. |
302
- | `CrudForm` (`useStore` + `children` store mode) | `form.values`, `form.isSubmitting`, `create`, `update`, `resetForm`, `setFormErrors`, `fetchAndPopulateForm`/`fetchById`/`fetchOne` | **No.** `createCrudStore` has no `form` state, no `resetForm`, no `setFormErrors`, and no `fetchAndPopulateForm`. Use `CrudForm`'s **fields mode** (`fields` array + `onSubmit`) with a `createCrudStore`-based store instead — call `create`/`update` yourself from `onSubmit`. |
303
-
304
- Given these gaps, treat `createCrudStore` as a solid base for **list fetching, item fetching, and CRUD mutations**, and either bridge the shape differences above or manage form/pagination-object state yourself alongside it.
305
-
306
- ---
307
-
308
- ## Best Practices
309
-
310
- ### 1. One store per resource
311
-
312
- ```js
313
- const useProductStore = createCrudStore({ apiClient, endpoint: '/products' })(create);
314
- const useOrderStore = createCrudStore({ apiClient, endpoint: '/orders' })(create);
315
- ```
316
-
317
- ### 2. Centralized API instance
318
-
319
- ```js
320
- // lib/api.js
321
- import axios from 'axios';
322
-
323
- const apiClient = axios.create({
324
- baseURL: import.meta.env.VITE_API_URL,
325
- headers: { 'Content-Type': 'application/json' },
326
- });
327
-
328
- apiClient.interceptors.request.use((config) => {
329
- const token = localStorage.getItem('token');
330
- if (token) config.headers.Authorization = `Bearer ${token}`;
331
- return config;
332
- });
333
-
334
- export default apiClient;
335
- ```
336
-
337
- ### 3. Handle loading/error/empty states
338
-
339
- ```jsx
340
- function ProductList() {
341
- const { items, loading, error, fetchList } = useProductStore();
342
-
343
- useEffect(() => {
344
- fetchList();
345
- }, []);
346
-
347
- if (loading) return <Loading />;
348
- if (error) return <ErrorState error={error} onRetry={fetchList} />;
349
- if (items.length === 0) return <EmptyState />;
350
-
351
- return <DataTable data={items} columns={columns} />;
352
- }
353
- ```
354
-
355
- ### 4. Form pattern (since the store has no form state)
356
-
357
- Manage form state locally (or with `react-hook-form`, or `CrudForm`'s fields mode) and call the store's `create`/`update`/`fetchOne` directly:
358
-
359
- ```jsx
360
- function ProductForm({ productId }) {
361
- const { fetchOne, create, update, submitting } = useProductStore();
362
- const [values, setValues] = useState({ name: '', price: '' });
363
- const isEditing = Boolean(productId);
364
-
365
- useEffect(() => {
366
- if (isEditing) {
367
- fetchOne(productId).then((item) => setValues(item));
368
- }
369
- }, [productId]);
370
-
371
- const handleSubmit = async (e) => {
372
- e.preventDefault();
373
- if (isEditing) {
374
- await update(productId, values);
375
- } else {
376
- await create(values);
377
- }
378
- };
379
-
380
- return (
381
- <form onSubmit={handleSubmit}>
382
- {/* fields bound to values/setValues */}
383
- <button disabled={submitting}>{submitting ? 'Saving...' : 'Save'}</button>
384
- </form>
385
- );
386
- }
387
- ```
388
-
389
- ### 5. Filtering pattern (remember `setFilters` replaces, not merges)
390
-
391
- ```jsx
392
- function ProductFilters() {
393
- const { filters, setFilters, fetchList } = useProductStore();
394
-
395
- const handleFilterChange = (key, value) => {
396
- setFilters({ ...filters, [key]: value }); // merge yourself
397
- };
398
-
399
- useEffect(() => {
400
- fetchList();
401
- }, [filters]);
402
-
403
- return (
404
- <div className="flex gap-4">
405
- <QSelect
406
- label="Category"
407
- value={filters.category}
408
- onChange={(val) => handleFilterChange('category', val)}
409
- options={categories}
410
- />
411
- <QSelect
412
- label="Status"
413
- value={filters.status}
414
- onChange={(val) => handleFilterChange('status', val)}
415
- options={statusOptions}
416
- />
417
- </div>
418
- );
419
- }
420
- ```
421
-
422
- ### 6. Bulk selection + bulk delete
423
-
424
- ```jsx
425
- function ProductList() {
426
- const { items, selectedIds, setSelectedIds, clearSelection, bulkDelete } = useProductStore();
427
-
428
- const toggleSelection = (id) => {
429
- setSelectedIds(
430
- selectedIds.includes(id) ? selectedIds.filter((i) => i !== id) : [...selectedIds, id],
431
- );
432
- };
433
-
434
- return (
435
- <div>
436
- <div className="flex gap-2 mb-4">
437
- <Button onClick={() => setSelectedIds(items.map((i) => i.id))}>Select All</Button>
438
- <Button onClick={clearSelection}>Clear Selection</Button>
439
- {selectedIds.length > 0 && (
440
- <Button variant="destructive" onClick={() => bulkDelete(selectedIds)}>
441
- Delete Selected ({selectedIds.length})
442
- </Button>
443
- )}
444
- </div>
445
- {items.map((item) => (
446
- <ProductCard
447
- key={item.id}
448
- item={item}
449
- selected={selectedIds.includes(item.id)}
450
- onSelect={() => toggleSelection(item.id)}
451
- />
452
- ))}
453
- </div>
454
- );
455
- }
456
- ```
1
+ # Store Factory Guide
2
+
3
+ Complete reference for `createCrudStore` (and `createStore`) in @bomjan133/react-crud-ui.
4
+
5
+ ## Table of Contents
6
+ 1. [Overview](#overview)
7
+ 2. [Basic Usage](#basic-usage)
8
+ 3. [`createStore` is currently broken under ESM](#createstore-is-currently-broken-under-esm)
9
+ 4. [Store Options](#store-options)
10
+ 5. [Store State](#store-state)
11
+ 6. [Store Actions](#store-actions)
12
+ 7. [API Request/Response Conventions](#api-requestresponse-conventions)
13
+ 8. [Extending with `extraActions`](#extending-with-extraactions)
14
+ 9. [Compatibility with `CrudList` / `CrudForm` / `CrudDetail`](#compatibility-with-crudlist--crudform--cruddetail)
15
+ 10. [Best Practices](#best-practices)
16
+
17
+ Everything below was verified by reading `src/store/createCrudStore.js` in full and running it directly against zustand 5 in Node — not inferred from the function names alone.
18
+
19
+ ---
20
+
21
+ ## Overview
22
+
23
+ `createCrudStore(options)` is a factory that builds a Zustand **state creator** for a single resource, wired to an Axios-compatible `apiClient`. It gives you:
24
+
25
+ - Flat list state (`items`, `page`, `pageSize`, `totalItems`, `totalPages`, `search`, `filters`, `sortColumn`, `sortDirection`, `selectedIds`)
26
+ - A single-item slot (`item`) for detail/edit views
27
+ - `loading` (list operations) and `submitting` (item operations) flags, plus `error`
28
+ - CRUD methods: `fetchList`, `fetchOne`, `create`, `update`, `delete`, `bulkDelete`, `replace`
29
+ - An `extraActions` escape hatch for anything custom
30
+
31
+ **It does not manage form state.** There is no `form.values`/`form.errors`, no `resetForm`/`setFormField`/`initForm` — none of that exists in this factory. If you need form state, either manage it yourself (`useState`/`react-hook-form`) or use `CrudForm`'s **fields mode** (`fields` + `onSubmit`), which is self-contained and doesn't need any of this. See [Compatibility](#compatibility-with-crudlist--crudform--cruddetail) below.
32
+
33
+ ---
34
+
35
+ ## Basic Usage
36
+
37
+ `createCrudStore(options)` does **not** return a ready-to-use hook by itself — it returns a Zustand *state creator function* that still needs zustand's own `create` passed into it. The correct pattern is:
38
+
39
+ ```js
40
+ // stores/useProductStore.js
41
+ import { create } from 'zustand';
42
+ import { createCrudStore } from '@bomjan133/react-crud-ui';
43
+ import apiClient from '@/lib/api'; // an Axios instance
44
+
45
+ const useProductStore = createCrudStore({
46
+ name: 'products',
47
+ apiClient,
48
+ endpoint: '/products',
49
+ })(create); // <-- note the trailing (create) call
50
+
51
+ export default useProductStore;
52
+ ```
53
+
54
+ Use it like any Zustand store:
55
+
56
+ ```jsx
57
+ import useProductStore from '@/stores/useProductStore';
58
+
59
+ function ProductList() {
60
+ const { items, loading, fetchList } = useProductStore();
61
+
62
+ useEffect(() => {
63
+ fetchList();
64
+ }, []);
65
+
66
+ return (
67
+ <div>
68
+ {items.map((product) => (
69
+ <div key={product.id}>{product.name}</div>
70
+ ))}
71
+ </div>
72
+ );
73
+ }
74
+ ```
75
+
76
+ ---
77
+
78
+ ## `createStore` is currently broken under ESM
79
+
80
+ The package also exports a `createStore(options)` "convenience wrapper" that's meant to skip the `(create)` call:
81
+
82
+ ```js
83
+ export const createStore = (options) => {
84
+ const { create } = require("zustand");
85
+ return create(createCrudStore(options));
86
+ };
87
+ ```
88
+
89
+ **This throws `ReferenceError: require is not defined` when you `import` the package (ESM)** — verified directly: calling `createStore({...})` after `import { createStore } from '@bomjan133/react-crud-ui'` fails immediately, because `require` doesn't exist in an ES module/browser bundle, and the published `dist/index.js` (ESM build) ships this `require("zustand")` call completely un-transformed. It only works if you consume the package's CommonJS build (`require('@bomjan133/react-crud-ui')`) directly, since `require` is a real function there.
90
+
91
+ **Until this is fixed upstream, don't use `createStore`. Use `createCrudStore(options)(create)` instead** (shown above) — it has no dependency on `require` and works identically in both ESM and CJS.
92
+
93
+ ---
94
+
95
+ ## Store Options
96
+
97
+ | Option | Type | Required | Default | Description |
98
+ |--------|------|----------|---------|-------------|
99
+ | `apiClient` | Axios instance (or compatible: needs `.get`/`.post`/`.patch`/`.put`/`.delete`) | **Yes** | - | Throws `"createCrudStore: apiClient is required"` if omitted. Not called `api` — see correction below. |
100
+ | `endpoint` | `string` | **Yes** | - | Throws `"createCrudStore: endpoint is required"` if omitted. Requests are built as `` `${endpoint}` ``, `` `${endpoint}/` `` (create), and `` `${endpoint}/${id}/` `` (fetchOne/update/delete/replace) — the trailing slashes are hardcoded, matching a Django REST Framework-style API. If your backend doesn't use trailing slashes, use `transformRequest`/a custom `apiClient` interceptor to compensate, or don't rely on this factory's endpoint building. |
101
+ | `name` | `string` | No | `"crud"` | Accepted but only used as a label — **not currently used for anything visible** (e.g. no Zustand devtools naming is wired up in this factory). |
102
+ | `transformResponse` | `(item) => item` | No | identity | Applied to each item in `fetchList` results and to the single item in `fetchOne`/`create`/`update`/`replace`. **Not called `transformItem`.** |
103
+ | `transformRequest` | `(data) => data` | No | identity | Applied to the payload before `create`/`update`/`replace` POST/PATCH/PUT calls. |
104
+ | `initialState` | `object` | No | `{}` | Merged into the store's initial state, after the built-in defaults — use this to add custom fields (it does **not** support a nested `filters: {...}` shorthand differently from any other key; it's a plain shallow merge). |
105
+ | `extraActions` | `object` | No | `{}` | Merged into the store, after all built-in actions — see [Extending](#extending-with-extraactions). **Not called `extend`, and not a function** — it's a plain object of actions (though you can build that object using `set`/`get` closures yourself before passing it in). |
106
+ | `idField` | `string` | No | `"id"` | Field name used to match items in `update`/`delete`/`bulkDelete`/`replace` (e.g. `item[idField] === id`). Set this to `"uuid"` if your API uses UUIDs under that key. |
107
+ | `listKey` | `string` | No | `"results"` | Key read from the list response body for the array of items — see [API conventions](#api-requestresponse-conventions). |
108
+ | `countKey` | `string` | No | `"count"` | Key read from the list response body for the total item count. |
109
+
110
+ > **Corrections vs. an earlier version of this doc:** the real required client option is `apiClient`, not `api`. There is no `transformItem`/`transformList`/`onFetchSuccess`/`onFetchError`/`onCreateSuccess`/`onUpdateSuccess`/`onDeleteSuccess`/`endpoints` (per-action endpoint overrides) option — none of these exist in the source. The only response-shaping hooks are `transformResponse`, `transformRequest`, `listKey`, and `countKey`.
111
+
112
+ ---
113
+
114
+ ## Store State
115
+
116
+ All of this is flat top-level state — there is no nested `pagination`/`form`/`current` object.
117
+
118
+ | Field | Type | Initial value | Description |
119
+ |-------|------|----------------|-------------|
120
+ | `items` | `array` | `[]` | Current page of list results. |
121
+ | `item` | `object \| null` | `null` | Currently-loaded single record (populated by `fetchOne`, kept in sync by `update`/`delete`/`replace`). |
122
+ | `loading` | `boolean` | `false` | True while `fetchList` or `fetchOne` is in flight. |
123
+ | `submitting` | `boolean` | `false` | True while `create`/`update`/`delete`/`bulkDelete`/`replace` is in flight. |
124
+ | `error` | `{ message, original, fieldErrors? } \| null` | `null` | Set by any failed request; cleared at the start of the next request, or via `clearError()`. `fieldErrors` (the raw `error.response.data`) is only attached by `create`/`update`/`replace`. |
125
+ | `page` | `number` | `1` | Current page. |
126
+ | `pageSize` | `number` | `15` | Items per page, sent as the `page_size` query param. |
127
+ | `totalItems` | `number` | `0` | Set from the last `fetchList` response. |
128
+ | `totalPages` | `number` | `0` | Computed as `Math.ceil(totalItems / pageSize)` after each `fetchList`. |
129
+ | `sortColumn` | `string \| null` | `null` | Set via `setSort`. |
130
+ | `sortDirection` | `string \| null` | `null` | Set via `setSort`; `"desc"` is sent as a `-` prefix on the `ordering` query param, anything else is sent unprefixed. |
131
+ | `search` | `string` | `""` | Set via `setSearch`; sent as the `search` query param. |
132
+ | `filters` | `object` | `{}` | Set (replaced wholesale, not merged) via `setFilters`; each key is spread directly into the query params. |
133
+ | `selectedIds` | `array` | `[]` | Set via `setSelectedIds`/`clearSelection`; also auto-pruned by `delete`/`bulkDelete`. |
134
+
135
+ > **There is no `pagination` object, no `current`/`itemLoading`/`itemError`, and no `form` state.** An earlier version of this doc described a `{ page, totalPages, total, perPage }` pagination object and a full form sub-state (`values`/`errors`/`isDirty`) — none of that exists in `createCrudStore`.
136
+
137
+ ---
138
+
139
+ ## Store Actions
140
+
141
+ ### List actions
142
+
143
+ ```js
144
+ const {
145
+ fetchList, // async (params = {}) => { items, totalItems, totalPages }
146
+ setPage, // (page) => void
147
+ setPageSize, // (pageSize) => void — also resets page to 1
148
+ setSearch, // (search) => void — also resets page to 1
149
+ setFilters, // (filters) => void — REPLACES filters wholesale, also resets page to 1
150
+ setSort, // (sortColumn, sortDirection) => void
151
+ clearError, // () => void
152
+ reset, // () => void — resets items/item/loading/submitting/error/page/search/filters/selectedIds/sort
153
+ } = useProductStore();
154
+
155
+ await fetchList(); // uses current page/pageSize/search/filters/sort
156
+ await fetchList({ page: 2 }); // merges extra params into the request (does not update store state)
157
+ setFilters({ status: 'active' }); // replaces the whole filters object — see caveat below
158
+ ```
159
+
160
+ > **`setFilters` replaces, it does not merge.** Calling `setFilters({ status: 'active' })` and later `setFilters({ category: 1 })` leaves `filters` as `{ category: 1 }` — the earlier `status` key is gone. If you need multiple independent filters, merge them yourself: `setFilters({ ...filters, category: 1 })`. There is no `clearFilters()` action — call `setFilters({})` instead.
161
+
162
+ ### Selection actions
163
+
164
+ ```js
165
+ const { selectedIds, setSelectedIds, clearSelection } = useProductStore();
166
+
167
+ setSelectedIds([1, 2, 3]);
168
+ clearSelection();
169
+ ```
170
+
171
+ ### Item actions
172
+
173
+ ```js
174
+ const { fetchOne } = useProductStore();
175
+
176
+ const product = await fetchOne(productId);
177
+ console.log(product.name);
178
+ ```
179
+
180
+ > There is no `fetchById` alias, and no `setCurrent`/`clearCurrent` — `item` is only ever set by `fetchOne` (and kept in sync by `update`/`delete`/`replace` when the ids match).
181
+
182
+ ### CRUD actions
183
+
184
+ ```js
185
+ const { create, update, delete: remove, bulkDelete, replace } = useProductStore();
186
+
187
+ const newProduct = await create({ name: 'New Product', price: 99.99 });
188
+ const updated = await update(productId, { name: 'Updated Name' });
189
+ await remove(productId); // the real action is named `delete` — alias it on destructure since `delete` is reserved in some contexts
190
+ await bulkDelete([1, 2, 3]); // deletes one-by-one via Promise.all, then updates items/totalItems/selectedIds
191
+ const replaced = await replace(productId, fullPayload); // PUT, full replace
192
+ ```
193
+
194
+ > **The delete method is named `delete`, not `remove`.** Since `delete` is a reserved word in object literal *shorthand* contexts in some older tooling, destructure it with a rename if needed: `const { delete: remove } = useProductStore();`. There is no separate `remove` action.
195
+
196
+ All of `create`/`update`/`delete`/`bulkDelete`/`replace` guard against concurrent calls (they no-op while `submitting` is already `true`, except `bulkDelete` which doesn't check `submitting` at all), and all reject (throw) on failure after populating `error`.
197
+
198
+ ---
199
+
200
+ ## API Request/Response Conventions
201
+
202
+ ### `fetchList` request
203
+
204
+ ```
205
+ GET {endpoint}?page=1&page_size=15&search=foo&ordering=-created_at&<...filters>
206
+ ```
207
+
208
+ - `page`/`page_size` always sent.
209
+ - `search` only sent if non-empty.
210
+ - `ordering` only sent if `sortColumn` is set; `sortDirection === 'desc'` prefixes it with `-`.
211
+ - Every key in `filters` is spread in directly, then any explicit `params` passed to `fetchList(params)` are spread in last (so they win over store state for that one call, without persisting it back to the store).
212
+ - Keys with `undefined` or `''` values are stripped before the request is sent.
213
+
214
+ ### `fetchList` response
215
+
216
+ Reads, in order of preference:
217
+ ```js
218
+ const items = data[listKey] || data.data || (Array.isArray(data) ? data : []);
219
+ const totalItems = data[countKey] || data.total || items.length;
220
+ ```
221
+ With the defaults (`listKey: "results"`, `countKey: "count"`), that means:
222
+
223
+ ```json
224
+ { "results": [ ... ], "count": 42 }
225
+ ```
226
+
227
+ is read out of the box. A response shaped like `{ "data": [...], "meta": { "total": 42 } }` requires either passing `listKey`/`countKey` (they only look at top-level keys, not nested `meta.total`) or handling reshaping yourself via a response interceptor on `apiClient`, since there is no `transformList` hook.
228
+
229
+ ### Single-item requests
230
+
231
+ - `fetchOne(id)` → `GET {endpoint}/{id}/`, result passed through `transformResponse`.
232
+ - `create(data)` → `POST {endpoint}/`, payload passed through `transformRequest` first, result through `transformResponse`.
233
+ - `update(id, data)` → `PATCH {endpoint}/{id}/`.
234
+ - `replace(id, data)` → `PUT {endpoint}/{id}/` (full replace).
235
+ - `delete(id)` / `bulkDelete(ids)` → `DELETE {endpoint}/{id}/` (one request per id for `bulkDelete`, run concurrently via `Promise.all`).
236
+
237
+ ### Error shape
238
+
239
+ Every action sets `error` to:
240
+ ```js
241
+ { message: string, original: Error, fieldErrors?: object }
242
+ ```
243
+ `message` is resolved from `error.response?.data?.message`, then `.detail`, then `error.message`, then a hardcoded fallback string. `fieldErrors` (the raw `error.response?.data`) is only attached for `create`/`update`/`replace` — useful for mapping server-side validation errors back onto form fields yourself.
244
+
245
+ ---
246
+
247
+ ## Extending with `extraActions`
248
+
249
+ `extraActions` is a plain object merged onto the store after all built-in state/actions — build it with closures over `set`/`get` yourself if it needs to read/write store state:
250
+
251
+ ```js
252
+ import { create } from 'zustand';
253
+ import { createCrudStore } from '@bomjan133/react-crud-ui';
254
+ import apiClient from '@/lib/api';
255
+
256
+ const useProductStoreCreator = (set, get) => ({
257
+ archive: async (id) => {
258
+ await apiClient.post(`/products/${id}/archive`);
259
+ await get().fetchList();
260
+ },
261
+ duplicate: async (id) => {
262
+ const { data } = await apiClient.post(`/products/${id}/duplicate`);
263
+ await get().fetchList();
264
+ return data;
265
+ },
266
+ });
267
+
268
+ // createCrudStore itself doesn't give you set/get ahead of time, so build
269
+ // extraActions inline using zustand's create, or pass simple stateless helpers:
270
+ const useProductStore = createCrudStore({
271
+ apiClient,
272
+ endpoint: '/products',
273
+ initialState: { viewMode: 'grid' },
274
+ extraActions: {
275
+ // Actions defined here only close over module-level values (like apiClient),
276
+ // not `set`/`get` — for state-aware extras, patch the store after creation instead:
277
+ },
278
+ })(create);
279
+
280
+ // State-aware extension pattern (recommended): wrap the created hook.
281
+ useProductStore.setState((state) => ({
282
+ setViewMode: (mode) => useProductStore.setState({ viewMode: mode }),
283
+ archive: async (id) => {
284
+ await apiClient.post(`/products/${id}/archive`);
285
+ await useProductStore.getState().fetchList();
286
+ },
287
+ }));
288
+ ```
289
+
290
+ > An earlier version of this doc showed an `extend: (set, get, store) => ({...})` function option — **that option does not exist**. `extraActions` is a plain object, so any action inside it that needs `set`/`get` must either close over the resulting hook itself (as shown above) or be added via `useProductStore.setState(...)` after creation.
291
+
292
+ ---
293
+
294
+ ## Compatibility with `CrudList` / `CrudForm` / `CrudDetail`
295
+
296
+ A store built with `createCrudStore` is **not** a drop-in for every `Q*`/`Crud*` component's `store`/`useStore` prop — each one expects a different shape:
297
+
298
+ | Component | What it needs from the store | Compatible with `createCrudStore`? |
299
+ |---|---|---|
300
+ | `CrudList` (`store` prop) | `items`, `loading`, `error`, `fetchList`, `delete`, `setPage`, `setPageSize`, `setFilters`, `sortColumn`/`sortDirection`/`setSort`, **and a nested `store.pagination` object** (`{ page, pageSize, total, totalPages }`) | **Partially.** `createCrudStore` gives you everything except `pagination` as a nested object — its pagination fields are flat (`page`/`pageSize`/`totalItems`/`totalPages`). Since `CrudList` reads `store?.pagination` directly, it won't find one and will silently fall back to `currentPage`/`pageSize`/`totalItems`/`totalPages` **props** (default `1`/`15`/`0`/`1`) instead of the store's real values — i.e. pagination will look stuck at page 1 unless you bridge it, e.g. `store={{ ...store, pagination: { page: store.page, pageSize: store.pageSize, total: store.totalItems, totalPages: store.totalPages } }}`. |
301
+ | `CrudDetail` (`useStore` prop) | `currentItem`, `loading`, `error`, `fetchById` (or `fetchOne`), `delete` | **Partially.** `createCrudStore` has `fetchOne` (used as the fallback) and `delete`, `loading`, `error` — but its single-item field is named `item`, not `currentItem`. `CrudDetail` reads `currentItem` specifically, so you'll need to bridge it too: `useStore={() => { const s = useProductStore(); return { ...s, currentItem: s.item }; }}`. |
302
+ | `CrudForm` (`useStore` + `children` store mode) | `form.values`, `form.isSubmitting`, `create`, `update`, `resetForm`, `setFormErrors`, `fetchAndPopulateForm`/`fetchById`/`fetchOne` | **No.** `createCrudStore` has no `form` state, no `resetForm`, no `setFormErrors`, and no `fetchAndPopulateForm`. Use `CrudForm`'s **fields mode** (`fields` array + `onSubmit`) with a `createCrudStore`-based store instead — call `create`/`update` yourself from `onSubmit`. |
303
+
304
+ Given these gaps, treat `createCrudStore` as a solid base for **list fetching, item fetching, and CRUD mutations**, and either bridge the shape differences above or manage form/pagination-object state yourself alongside it.
305
+
306
+ ---
307
+
308
+ ## Best Practices
309
+
310
+ ### 1. One store per resource
311
+
312
+ ```js
313
+ const useProductStore = createCrudStore({ apiClient, endpoint: '/products' })(create);
314
+ const useOrderStore = createCrudStore({ apiClient, endpoint: '/orders' })(create);
315
+ ```
316
+
317
+ ### 2. Centralized API instance
318
+
319
+ ```js
320
+ // lib/api.js
321
+ import axios from 'axios';
322
+
323
+ const apiClient = axios.create({
324
+ baseURL: import.meta.env.VITE_API_URL,
325
+ headers: { 'Content-Type': 'application/json' },
326
+ });
327
+
328
+ apiClient.interceptors.request.use((config) => {
329
+ const token = localStorage.getItem('token');
330
+ if (token) config.headers.Authorization = `Bearer ${token}`;
331
+ return config;
332
+ });
333
+
334
+ export default apiClient;
335
+ ```
336
+
337
+ ### 3. Handle loading/error/empty states
338
+
339
+ ```jsx
340
+ function ProductList() {
341
+ const { items, loading, error, fetchList } = useProductStore();
342
+
343
+ useEffect(() => {
344
+ fetchList();
345
+ }, []);
346
+
347
+ if (loading) return <Loading />;
348
+ if (error) return <ErrorState error={error} onRetry={fetchList} />;
349
+ if (items.length === 0) return <EmptyState />;
350
+
351
+ return <DataTable data={items} columns={columns} />;
352
+ }
353
+ ```
354
+
355
+ ### 4. Form pattern (since the store has no form state)
356
+
357
+ Manage form state locally (or with `react-hook-form`, or `CrudForm`'s fields mode) and call the store's `create`/`update`/`fetchOne` directly:
358
+
359
+ ```jsx
360
+ function ProductForm({ productId }) {
361
+ const { fetchOne, create, update, submitting } = useProductStore();
362
+ const [values, setValues] = useState({ name: '', price: '' });
363
+ const isEditing = Boolean(productId);
364
+
365
+ useEffect(() => {
366
+ if (isEditing) {
367
+ fetchOne(productId).then((item) => setValues(item));
368
+ }
369
+ }, [productId]);
370
+
371
+ const handleSubmit = async (e) => {
372
+ e.preventDefault();
373
+ if (isEditing) {
374
+ await update(productId, values);
375
+ } else {
376
+ await create(values);
377
+ }
378
+ };
379
+
380
+ return (
381
+ <form onSubmit={handleSubmit}>
382
+ {/* fields bound to values/setValues */}
383
+ <button disabled={submitting}>{submitting ? 'Saving...' : 'Save'}</button>
384
+ </form>
385
+ );
386
+ }
387
+ ```
388
+
389
+ ### 5. Filtering pattern (remember `setFilters` replaces, not merges)
390
+
391
+ ```jsx
392
+ function ProductFilters() {
393
+ const { filters, setFilters, fetchList } = useProductStore();
394
+
395
+ const handleFilterChange = (key, value) => {
396
+ setFilters({ ...filters, [key]: value }); // merge yourself
397
+ };
398
+
399
+ useEffect(() => {
400
+ fetchList();
401
+ }, [filters]);
402
+
403
+ return (
404
+ <div className="flex gap-4">
405
+ <QSelect
406
+ label="Category"
407
+ value={filters.category}
408
+ onChange={(val) => handleFilterChange('category', val)}
409
+ options={categories}
410
+ />
411
+ <QSelect
412
+ label="Status"
413
+ value={filters.status}
414
+ onChange={(val) => handleFilterChange('status', val)}
415
+ options={statusOptions}
416
+ />
417
+ </div>
418
+ );
419
+ }
420
+ ```
421
+
422
+ ### 6. Bulk selection + bulk delete
423
+
424
+ ```jsx
425
+ function ProductList() {
426
+ const { items, selectedIds, setSelectedIds, clearSelection, bulkDelete } = useProductStore();
427
+
428
+ const toggleSelection = (id) => {
429
+ setSelectedIds(
430
+ selectedIds.includes(id) ? selectedIds.filter((i) => i !== id) : [...selectedIds, id],
431
+ );
432
+ };
433
+
434
+ return (
435
+ <div>
436
+ <div className="flex gap-2 mb-4">
437
+ <Button onClick={() => setSelectedIds(items.map((i) => i.id))}>Select All</Button>
438
+ <Button onClick={clearSelection}>Clear Selection</Button>
439
+ {selectedIds.length > 0 && (
440
+ <Button variant="destructive" onClick={() => bulkDelete(selectedIds)}>
441
+ Delete Selected ({selectedIds.length})
442
+ </Button>
443
+ )}
444
+ </div>
445
+ {items.map((item) => (
446
+ <ProductCard
447
+ key={item.id}
448
+ item={item}
449
+ selected={selectedIds.includes(item.id)}
450
+ onSelect={() => toggleSelection(item.id)}
451
+ />
452
+ ))}
453
+ </div>
454
+ );
455
+ }
456
+ ```