react-form-action 2.2.0 → 2.3.0

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.
package/README.md CHANGED
@@ -60,59 +60,53 @@ export const subscribeAction = formAction
60
60
  "use client";
61
61
 
62
62
  import {
63
- Action,
64
63
  Form,
65
64
  Pending,
65
+ createComponents,
66
66
  useActionContext,
67
67
  } from "react-form-action/client";
68
68
 
69
69
  import { subscribeAction } from "./action";
70
70
 
71
- const { FieldError } = createComponents(subscribeAction);
71
+ const { FieldError, Success } = createComponents(subscribeAction);
72
72
 
73
73
  export function SubscribeForm() {
74
- return (
75
- <Action action={subscribeAction} initialData="">
76
- <SuccessMessage />
77
- <Form>
78
- <input name="email" />
79
- {/*💡 The name prop supports autocompletion */}
80
- <FieldError name="email" />
81
- </Form>
82
- <SubmitButton />
83
- <Pending>Please wait...</Pending>
84
- </Action>
85
- );
86
- }
87
-
88
- function SuccessMessage() {
89
- // Pass action to cast the type of the "data" value
90
- const { isSuccess, data } = useActionContext(subscribeAction);
91
-
92
- return isSuccess && <p>Email {data} was registered.</p>;
93
- }
94
-
95
- function SubmitButton() {
96
- // no need for action when reading a generic value
97
- const { isPending } = useActionContext();
74
+ const { isPending, isFailure, error, data } =
75
+ useActionContext(subscribeAction);
98
76
 
99
77
  return (
100
- <button type="submit" disabled={isPending}>
101
- {isPending ? "Submitting..." : "Submit"}
102
- </button>
78
+ <Form>
79
+ <Success>
80
+ <p>✅ Email {data} was registered.</p>
81
+ </Success>
82
+ <input name="email" />
83
+ {/*💡 The FieldError "name" prop supports autocompletion */}
84
+ <FieldError name="email" />
85
+ <button type="submit" disabled={isPending}>
86
+ {isPending ? "🌀 Submitting..." : "Submit"}
87
+ </button>
88
+ <Pending>Please wait...</Pending>
89
+ </Form>
103
90
  );
104
91
  }
105
92
  ```
106
93
 
107
- #### 3️⃣ Render the form on a Page
94
+ #### 3️⃣ Provide the `<Action>` context on a Page
108
95
 
109
96
  ```tsx
110
97
  // app/subscribe/page.tsx
111
98
 
99
+ import { Action } from "react-form-action/client";
100
+
112
101
  import { SubscribeForm } from "./SubscribeForm";
102
+ import { subscribeAction } from "./action";
113
103
 
114
- export function Page() {
115
- return <SubscribeForm />;
104
+ export default function Page() {
105
+ return (
106
+ <Action action={subscribeAction} initialData="">
107
+ <SubscribeForm />
108
+ </Action>
109
+ );
116
110
  }
117
111
  ```
118
112
 
@@ -141,7 +135,7 @@ const authAction = formAction
141
135
  .use(async ({ ctx: { t } }) =>
142
136
  console.log("🎉 context enhanced by previous middlewares 🎉", t)
143
137
  )
144
- .error(({ error }) => {
138
+ .error(async ({ error }) => {
145
139
  if (error instanceof DbError) {
146
140
  return error.custom.code;
147
141
  } else {
package/dist/client.d.mts CHANGED
@@ -49,21 +49,27 @@ type Paths<Err> = {
49
49
  [k in keyof Err]: k extends string ? Err[k] extends object ? `${k}${typeof SEPARATOR}${Paths<Err[k]>}` : k : never;
50
50
  }[keyof Err];
51
51
  type InferZodErrorPaths<Errors> = Errors extends ZodFormattedError<infer E> ? Paths<E> : never;
52
- type ZodFieldErrorProps<Errors extends ZodFormattedError<any>> = {
52
+ type ZodFieldErrorProps<Errors extends ZodFormattedError<any>, Name extends "" | InferZodErrorPaths<Errors>> = {
53
53
  errors: Errors;
54
- name?: "" | InferZodErrorPaths<Errors>;
55
- } & Partial<RenderProp<{
54
+ name?: Name;
55
+ } & Partial<RenderProp<ZodFieldErrorChildrenProps<Name>>>;
56
+ type ZodFieldErrorChildrenProps<Name> = {
57
+ name: Name;
58
+ error?: string;
56
59
  errors: readonly string[];
57
- }>>;
58
- declare function ZodFieldError<Errors extends ZodFormattedError<any>>({ errors, name, children, }: ZodFieldErrorProps<Errors>): React__default.ReactNode;
60
+ };
61
+ declare const noError: Readonly<{
62
+ _errors: readonly string[];
63
+ }>;
64
+ declare function ZodFieldError<Errors extends ZodFormattedError<any>, Name extends "" | InferZodErrorPaths<Errors> = "">({ errors, name, children, }: ZodFieldErrorProps<Errors, Name>): React__default.ReactNode;
59
65
 
60
66
  /**
61
67
  * Creates a typed components for actions created with the formAction builder.
62
68
  */
63
69
  declare function createComponents<Data, Error, ValidationError extends ZodFormattedError<any>>(action: FormAction<Data, Error, ValidationError>): {
64
- FieldError: ({ name, }: PropsWithChildren<{
65
- name?: "" | InferZodErrorPaths<ValidationError>;
66
- }>) => false | React__default.JSX.Element;
70
+ FieldError: <Name extends "" | InferZodErrorPaths<ValidationError>>({ name, children, }: {
71
+ name?: Name;
72
+ } & Partial<RenderProp<ZodFieldErrorChildrenProps<Name>>>) => React__default.JSX.Element;
67
73
  Success: ({ children, }: PropsWithChildren | RP<{
68
74
  isSuccess: false;
69
75
  data: Data | null;
@@ -82,4 +88,4 @@ declare function Pending({ children, }: PropsWithChildren | RP<{
82
88
  isPending: boolean;
83
89
  }>): React.ReactNode;
84
90
 
85
- export { Action, type ActionContextState, type ActionProps, Form, type FormProps, FormStatus, type InferZodErrorPaths, type Paths, Pending, ZodFieldError, type ZodFieldErrorProps, createComponents, useActionContext };
91
+ export { Action, type ActionContextState, type ActionProps, Form, type FormProps, FormStatus, type InferZodErrorPaths, type Paths, Pending, ZodFieldError, type ZodFieldErrorChildrenProps, type ZodFieldErrorProps, createComponents, noError, useActionContext };
package/dist/client.mjs CHANGED
@@ -1 +1 @@
1
- "use client";import{a as c}from"./chunk-HL47DG4L.mjs";import f from"react";import{createContext as E,use as x}from"react";import{useActionState as y}from"react";var p={isInitial:!1,isInvalid:!1,isFailure:!1,isSuccess:!1},u=E(null);function a(t){let o=x(u);if(!o)throw new Error("ActionContext must be initialized before use. Is your useActionContext hook wrapped with an <Action> Component?");return o}function g({children:t,action:o,initialData:i,permalink:e}){let[r,n,s]=y(o,c(i),e),d=r.type==="initial"?{...r,...p,action:n,isPending:s,isInitial:!0}:r.type==="invalid"?{...r,...p,action:n,isPending:s,isInvalid:!0}:r.type==="failure"?{...r,...p,action:n,isPending:s,isFailure:!0}:{...r,...p,action:n,isPending:s,isSuccess:!0};return f.createElement(u,{value:d},t)}import S,{startTransition as A}from"react";function R({autoReset:t=!1,...o}){let{action:i}=a();return S.createElement("form",{...t?{action:i}:{onSubmit:r=>{r.preventDefault();let n=r.currentTarget;A(()=>{i(new FormData(n))})}},...o})}import C from"react";import m from"react";var F=".",P=Object.freeze({_errors:Object.freeze([])});function l({errors:t,name:o="",children:i=({errors:e})=>m.createElement(m.Fragment,null,e[0])}){if(o.length===0)return i({errors:t._errors});let e=o.split(F),r=t;for(;e.length;){let n=e.shift();r=r[n]??P}return i({errors:r._errors})}function $(t){function o({name:e}){let{isInvalid:r,validationError:n}=a(t);return r&&C.createElement(l,{errors:n,name:e})}function i({children:e}){let{isSuccess:r,data:n}=a(t);return typeof e=="function"?e(r?{isSuccess:r,data:n}:{isSuccess:r,data:n}):r&&e}return{FieldError:o,Success:i}}import{useFormStatus as h}from"react-dom";function X({children:t}){return t(h())}function q({children:t}){let{isPending:o}=a();return typeof t=="function"?t({isPending:o}):o&&t}export{g as Action,R as Form,X as FormStatus,q as Pending,l as ZodFieldError,$ as createComponents,a as useActionContext};
1
+ "use client";import{a as m}from"./chunk-HL47DG4L.mjs";import y from"react";import{createContext as P,use as S}from"react";import{useActionState as F}from"react";var p={isInitial:!1,isInvalid:!1,isFailure:!1,isSuccess:!1},u=P(null);function a(t){let o=S(u);if(!o)throw new Error("ActionContext must be initialized before use. Is your useActionContext hook wrapped with an <Action> Component?");return o}function w({children:t,action:o,initialData:i,permalink:e}){let[r,n,s]=F(o,m(i),e),l=r.type==="initial"?{...r,...p,action:n,isPending:s,isInitial:!0}:r.type==="invalid"?{...r,...p,action:n,isPending:s,isInvalid:!0}:r.type==="failure"?{...r,...p,action:n,isPending:s,isFailure:!0}:{...r,...p,action:n,isPending:s,isSuccess:!0};return y.createElement(u,{value:l},t)}import A,{startTransition as C}from"react";function N({autoReset:t=!1,...o}){let{action:i}=a();return A.createElement("form",{...t?{action:i}:{onSubmit:r=>{r.preventDefault();let n=r.currentTarget;C(()=>{i(new FormData(n))})}},...o})}import c from"react";import f from"react";var h=".",d=Object.freeze({_errors:Object.freeze([])});function E({errors:t,name:o="",children:i=({error:e})=>f.createElement(f.Fragment,null,e)}){if(o.length===0)return i({name:o,error:t._errors[0],errors:t._errors});let e=o.split(h),r=t;for(;e.length;){let n=e.shift();r=r[n]??d}return i({name:o,error:r._errors[0],errors:r._errors})}function J(t){function o({name:e,children:r}){let{isInvalid:n,validationError:s}=a(t);return c.createElement(E,{errors:s??d,name:e},r??(({error:x})=>n&&c.createElement(c.Fragment,null,x)))}function i({children:e}){let{isSuccess:r,data:n}=a(t);return typeof e=="function"?e(r?{isSuccess:r,data:n}:{isSuccess:r,data:n}):r&&e}return{FieldError:o,Success:i}}import{useFormStatus as k}from"react-dom";function H({children:t}){return t(k())}function B({children:t}){let{isPending:o}=a();return typeof t=="function"?t({isPending:o}):o&&t}export{w as Action,N as Form,H as FormStatus,B as Pending,E as ZodFieldError,J as createComponents,d as noError,a as useActionContext};
package/dist/index.d.mts CHANGED
@@ -8,6 +8,10 @@ type Flatten<T> = Identity<{
8
8
  [K in keyof T]: T[K];
9
9
  }>;
10
10
  type Identity<T> = T;
11
+ type ErrorHandler<Context, Err> = (params: {
12
+ error: unknown;
13
+ ctx: Context;
14
+ }) => Promise<Err>;
11
15
  type InitialContext = Record<"formData", FormData>;
12
16
  /**
13
17
  * Action without schema has no input.
@@ -45,10 +49,7 @@ type FormActionBuilder<Schema extends ZodTypeAny | EmptyInput, Err = Error, Cont
45
49
  * @param processError A function which receives action's errors.
46
50
  * @returns FormActionBuilder
47
51
  */
48
- error: <Err>(processError: (params: {
49
- error: unknown;
50
- ctx: Context;
51
- }) => Err) => FormActionBuilder<Schema, Err, Context>;
52
+ error: <Err>(processError: ErrorHandler<Context, Err>) => FormActionBuilder<Schema, Err, Context>;
52
53
  };
53
54
  declare const formAction: FormActionBuilder<typeof emptyInput, Error, InitialContext>;
54
55
 
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{a as A,b as p}from"./chunk-HL47DG4L.mjs";import{ZodFirstPartyTypeKind as C}from"zod";import{zfd as w}from"zod-form-data";var x=Symbol();function i(n,o=[],r){async function f(t){let e={formData:t};for(let a of o){let s=await a({ctx:e});e={...e,...s}}return e}return{input(t){if(n===x)return i(t,o,r);if(n._def.effect)throw new Error("Previous input is not augmentable because it contains an effect.");if(t._def.effect)throw new Error("Your input contains effect which prevents merging it with the previous inputs.");if(n._def.typeName===C.ZodObject){let e=n.merge(t);return i(e,o)}else throw Error("Merging inputs works only for object schemas without effects.")},use(t){return i(n,[...o,t],r)},error(t){return i(n,o,t)},run:n===x?t=>p(({success:e,failure:a})=>async(s,m)=>{let d=await f(m);try{return e(await t({ctx:d}))}catch(c){if(r)return a(r({error:c,ctx:d}));throw c}}):n===x?void 0:t=>p(({success:e,failure:a,invalid:s})=>{let m=w.formData(n);return async(d,c)=>{let y=await f(c),u=m.safeParse(c);if(!u.success)return s(u.error.format());let h=u.data;try{return e(await t({input:h,ctx:y}))}catch(S){if(r)return a(r({error:S,ctx:y}));throw S}}})}}var N=i(x);export{p as createFormAction,N as formAction,A as initial};
1
+ import{a as A,b as p}from"./chunk-HL47DG4L.mjs";import{ZodFirstPartyTypeKind as C}from"zod";import{zfd as E}from"zod-form-data";var d=Symbol();function i(n,o=[],r){async function f(t){let e={formData:t};for(let a of o){let s=await a({ctx:e});e={...e,...s}}return e}return{input(t){if(n===d)return i(t,o,r);if(n._def.effect)throw new Error("Previous input is not augmentable because it contains an effect.");if(t._def.effect)throw new Error("Your input contains effect which prevents merging it with the previous inputs.");if(n._def.typeName===C.ZodObject){let e=n.merge(t);return i(e,o)}else throw Error("Merging inputs works only for object schemas without effects.")},use(t){return i(n,[...o,t],r)},error(t){return i(n,o,t)},run:n===d?t=>p(({success:e,failure:a})=>async(s,x)=>{let m=await f(x);try{return e(await t({ctx:m}))}catch(c){if(r)return a(await r({error:c,ctx:m}));throw c}}):n===d?void 0:t=>p(({success:e,failure:a,invalid:s})=>{let x=E.formData(n);return async(m,c)=>{let y=await f(c),u=x.safeParse(c);if(!u.success)return s(u.error.format());let h=u.data;try{return e(await t({input:h,ctx:y}))}catch(S){if(r)return a(await r({error:S,ctx:y}));throw S}}})}}var N=i(d);export{p as createFormAction,N as formAction,A as initial};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-form-action",
3
- "version": "2.2.0",
3
+ "version": "2.3.0",
4
4
  "description": "State management helpers for the react form actions.",
5
5
  "repository": {
6
6
  "type": "git",