forked from Lilly-Protocol/lily-frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuse-form-action.ts
More file actions
63 lines (55 loc) · 1.74 KB
/
Copy pathuse-form-action.ts
File metadata and controls
63 lines (55 loc) · 1.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
"use client";
import { useActionState, useCallback } from "react";
export type FieldErrors = Record<string, string[]>;
export interface FormActionState<TData = unknown> {
fieldErrors: FieldErrors | null;
formError: string | null;
data: TData | null;
}
export interface UseFormActionResult<TData = unknown> {
state: FormActionState<TData>;
pending: boolean;
reset: () => void;
submit: (payload?: FormData) => void;
}
const INITIAL_STATE: FormActionState<unknown> = {
fieldErrors: null,
formError: null,
data: null,
};
/**
* Thin wrapper around React 19's `useActionState` that normalises the shape
* returned by server/client actions into `{ fieldErrors, formError, data }`.
*
* Works with both server actions and regular async client functions. The
* action MUST return a `FormActionState`-compatible object on success or
* failure so the hook can surface structured feedback to the UI.
*/
export function useFormAction<TData = unknown>(
action: (
prevState: FormActionState<TData>,
payload: FormData,
) => Promise<FormActionState<TData>> | FormActionState<TData>,
): UseFormActionResult<TData> {
const [state, dispatch, pending] = useActionState<
FormActionState<TData>,
FormData
>(async (prev, payload) => {
try {
return await action(prev, payload);
} catch (err) {
const message =
err instanceof Error ? err.message : "Unexpected error occurred.";
return { ...INITIAL_STATE, formError: message } as FormActionState<TData>;
}
}, INITIAL_STATE as FormActionState<TData>);
const reset = useCallback(() => {
dispatch(new FormData());
}, [dispatch]);
return {
state,
pending,
reset,
submit: dispatch,
};
}