Skip to content
File

Blob: src/client/hooks/use-resource-form.ts

typescript62 lines
1import { useCallback, useState } from "react";
2 
3interface UseResourceFormOptions {
4 canCancel?: () => boolean;
5}
6 
7interface UseResourceFormResult<TId extends string> {
8 creating: boolean;
9 editingId: TId | null;
10 formActive: boolean;
11 formError: string | null;
12 startCreate: () => void;
13 startEdit: (id: TId) => void;
14 cancel: () => void;
15 close: () => void;
16 setFormError: (message: string | null) => void;
17}
18 
19export const useResourceForm = <TId extends string = string>(
20 options: UseResourceFormOptions = {},
21): UseResourceFormResult<TId> => {
22 const { canCancel } = options;
23 const [creating, setCreating] = useState(false);
24 const [editingId, setEditingId] = useState<TId | null>(null);
25 const [formError, setFormError] = useState<string | null>(null);
26 
27 const startCreate = useCallback(() => {
28 setEditingId(null);
29 setFormError(null);
30 setCreating(true);
31 }, []);
32 
33 const startEdit = useCallback((id: TId) => {
34 setCreating(false);
35 setFormError(null);
36 setEditingId(id);
37 }, []);
38 
39 const close = useCallback(() => {
40 setCreating(false);
41 setEditingId(null);
42 setFormError(null);
43 }, []);
44 
45 const cancel = useCallback(() => {
46 if (canCancel && canCancel() === false) return;
47 close();
48 }, [canCancel, close]);
49 
50 return {
51 creating,
52 editingId,
53 formActive: creating || editingId !== null,
54 formError,
55 startCreate,
56 startEdit,
57 cancel,
58 close,
59 setFormError,
60 };
61};