react-form-action 2.4.1 → 2.4.2
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 +498 -497
- package/dist/chunk-LPB4R2UB.mjs +1 -0
- package/dist/client.mjs +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
- package/dist/chunk-22TNX3DL.mjs +0 -1
package/README.md
CHANGED
|
@@ -1,497 +1,498 @@
|
|
|
1
|
-
# react-form-action
|
|
2
|
-
|
|
3
|
-
End-to-end typesafe success, error & validation state control for Next.js form actions.
|
|
4
|
-
|
|
5
|
-
## Features
|
|
6
|
-
|
|
7
|
-
**Action Creator**
|
|
8
|
-
|
|
9
|
-
- ✅ Provides envelope objects with `"initial" | "invalid" | "success" | "failure"` response types.
|
|
10
|
-
- ✅ Define generic payload for each of the response type.
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
- ✅
|
|
16
|
-
- ✅ Reuse
|
|
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
|
-
import {
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
.
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
<
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
import {
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
import {
|
|
125
|
-
import {
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
};
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
.use(
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
//
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
.
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
import {
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
//
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
import
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
<input name="
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
<
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
//
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
<
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
1
|
+
# react-form-action
|
|
2
|
+
|
|
3
|
+
End-to-end typesafe success, error & validation state control for Next.js form actions.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
**Action Creator**
|
|
8
|
+
|
|
9
|
+
- ✅ Provides envelope objects with `"initial" | "invalid" | "success" | "failure"` response types.
|
|
10
|
+
- ✅ Define generic payload for each of the response type.
|
|
11
|
+
- ✅ Bind action arguments.
|
|
12
|
+
|
|
13
|
+
**tRPC-like Form Action builder**
|
|
14
|
+
|
|
15
|
+
- ✅ Define payload schema with the `.input(zodSchema)` to validate the `formData`
|
|
16
|
+
- ✅ Reuse business logic with the `.use(middleware)` method.
|
|
17
|
+
- ✅ Reuse error handling with the `.error(handler)`.
|
|
18
|
+
|
|
19
|
+
**React Context access with the `<Action action={myFormAction} />` component**
|
|
20
|
+
|
|
21
|
+
- ✅ The `useActionState()` accessible via the `useActionContext()` hook.
|
|
22
|
+
- ✅ Computes progress flags like `isInvalid`, `isSuccess` based on the envelope type.
|
|
23
|
+
|
|
24
|
+
**Context-bound `<Form />` component**
|
|
25
|
+
|
|
26
|
+
- ✅ Reads the `action` from the `<Action />` context.
|
|
27
|
+
- ✅ Opt-out from the default form reset after action submit.
|
|
28
|
+
|
|
29
|
+
## Install
|
|
30
|
+
|
|
31
|
+
```
|
|
32
|
+
npm i react-form-action zod-form-data
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
<a aria-label="NPM version" href="https://www.npmjs.com/package/react-form-action">
|
|
36
|
+
<img alt="NPM Version" src="https://img.shields.io/npm/v/react-form-action?style=for-the-badge&labelColor=24292e">
|
|
37
|
+
</a>
|
|
38
|
+
|
|
39
|
+
## Getting Started
|
|
40
|
+
|
|
41
|
+
#### 1️⃣ Create a Server Action
|
|
42
|
+
|
|
43
|
+
```tsx
|
|
44
|
+
// app/subscribe/action.ts
|
|
45
|
+
"use server";
|
|
46
|
+
|
|
47
|
+
import { formAction } from "react-form-action";
|
|
48
|
+
import { z } from "zod";
|
|
49
|
+
|
|
50
|
+
export const subscribeAction = formAction
|
|
51
|
+
.input(z.object({ email: z.string().email() }))
|
|
52
|
+
.run(async ({ input }) => {
|
|
53
|
+
return input.email;
|
|
54
|
+
});
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
#### 2️⃣ Create a Client Form Component
|
|
58
|
+
|
|
59
|
+
```tsx
|
|
60
|
+
// app/subscribe/form.tsx
|
|
61
|
+
"use client";
|
|
62
|
+
|
|
63
|
+
import {
|
|
64
|
+
Form,
|
|
65
|
+
Pending,
|
|
66
|
+
createComponents,
|
|
67
|
+
useActionContext,
|
|
68
|
+
} from "react-form-action/client";
|
|
69
|
+
|
|
70
|
+
import { subscribeAction } from "./action";
|
|
71
|
+
|
|
72
|
+
const { FieldError, Success } = createComponents(subscribeAction);
|
|
73
|
+
|
|
74
|
+
export function SubscribeForm() {
|
|
75
|
+
const { isPending, isFailure, error, data } =
|
|
76
|
+
useActionContext(subscribeAction);
|
|
77
|
+
|
|
78
|
+
return (
|
|
79
|
+
<Form>
|
|
80
|
+
<Success>
|
|
81
|
+
<p>✅ Email {data} was registered.</p>
|
|
82
|
+
</Success>
|
|
83
|
+
<input name="email" />
|
|
84
|
+
{/*💡 The FieldError "name" prop supports autocompletion */}
|
|
85
|
+
<FieldError name="email" />
|
|
86
|
+
<button type="submit" disabled={isPending}>
|
|
87
|
+
{isPending ? "🌀 Submitting..." : "Submit"}
|
|
88
|
+
</button>
|
|
89
|
+
<Pending>Please wait...</Pending>
|
|
90
|
+
</Form>
|
|
91
|
+
);
|
|
92
|
+
}
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
#### 3️⃣ Provide the `<Action>` context on a Page
|
|
96
|
+
|
|
97
|
+
```tsx
|
|
98
|
+
// app/subscribe/page.tsx
|
|
99
|
+
|
|
100
|
+
import { Action } from "react-form-action/client";
|
|
101
|
+
|
|
102
|
+
import { subscribeAction } from "./action";
|
|
103
|
+
import { SubscribeForm } from "./form";
|
|
104
|
+
|
|
105
|
+
export default function Page() {
|
|
106
|
+
return (
|
|
107
|
+
<Action action={subscribeAction} initialData="">
|
|
108
|
+
<SubscribeForm />
|
|
109
|
+
</Action>
|
|
110
|
+
);
|
|
111
|
+
}
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
## Usage
|
|
115
|
+
|
|
116
|
+
### `formAction` builder
|
|
117
|
+
|
|
118
|
+
The [`zod-form-data`](https://www.npmjs.com/package/zod-form-data) powered action builder.
|
|
119
|
+
|
|
120
|
+
```ts
|
|
121
|
+
// app/actions/auth.ts
|
|
122
|
+
"use server";
|
|
123
|
+
|
|
124
|
+
import { formAction } from "react-form-action";
|
|
125
|
+
import { z } from "zod";
|
|
126
|
+
import { cookies } from "next/headers";
|
|
127
|
+
|
|
128
|
+
const i18nMiddleware = async () => {
|
|
129
|
+
const { t } = await useTranslation("auth", cookies().get("i18n")?.value);
|
|
130
|
+
// will be added to context
|
|
131
|
+
return { t };
|
|
132
|
+
};
|
|
133
|
+
|
|
134
|
+
const authAction = formAction
|
|
135
|
+
.use(i18nMiddleware)
|
|
136
|
+
.use(async ({ ctx: { t } }) =>
|
|
137
|
+
console.log("🎉 context enhanced by previous middlewares 🎉", t)
|
|
138
|
+
)
|
|
139
|
+
.error(async ({ error }) => {
|
|
140
|
+
if (error instanceof DbError) {
|
|
141
|
+
return error.custom.code;
|
|
142
|
+
} else {
|
|
143
|
+
// unknown error
|
|
144
|
+
// default Next.js error handling (error.js boundary)
|
|
145
|
+
throw error;
|
|
146
|
+
}
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
export const signIn = authAction
|
|
150
|
+
.input(z.object({ email: z.string().email() }))
|
|
151
|
+
// 🎉 extend the previous input (only without refinements and transforms)
|
|
152
|
+
.input(z.object({ password: z.string() }))
|
|
153
|
+
.run(async ({ ctx: { t }, input: { email, password } }) => {
|
|
154
|
+
// Type inferred: {email: string, password: string}
|
|
155
|
+
|
|
156
|
+
await db.signIn({ email, password });
|
|
157
|
+
|
|
158
|
+
return t("verificationEmail.success");
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
export const signUp = authAction
|
|
162
|
+
.input(
|
|
163
|
+
z
|
|
164
|
+
.object({
|
|
165
|
+
email: z.string().email(),
|
|
166
|
+
password: z.string(),
|
|
167
|
+
confirm: z.string(),
|
|
168
|
+
})
|
|
169
|
+
.refine((data) => data.password === data.confirm, {
|
|
170
|
+
message: "Passwords don't match",
|
|
171
|
+
path: ["confirm"],
|
|
172
|
+
})
|
|
173
|
+
) // if using refinement, only one input call is permited, as schema with ZodEffects is not extendable.
|
|
174
|
+
.run(async ({ ctx: { t }, input: { email, password } }) => {
|
|
175
|
+
// 🎉 passwords match!
|
|
176
|
+
|
|
177
|
+
const tokenData = await db.signUp({ email, password });
|
|
178
|
+
|
|
179
|
+
if (!tokenData) {
|
|
180
|
+
return t("signUp.emailVerificationRequired");
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
return t("singUp.success");
|
|
184
|
+
});
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
### Action Creator
|
|
188
|
+
|
|
189
|
+
Low-level action creator, which provides the `success`, `failure` and `invalid` envelope constructors. With the `createFormAction` you must handle the native `FormData` by yourself.
|
|
190
|
+
|
|
191
|
+
```ts
|
|
192
|
+
"use server";
|
|
193
|
+
|
|
194
|
+
import { createFormAction } from "react-form-action";
|
|
195
|
+
import { z } from "zod";
|
|
196
|
+
|
|
197
|
+
// Define custom serializable error & success data types
|
|
198
|
+
type ErrorData = {
|
|
199
|
+
message: string;
|
|
200
|
+
};
|
|
201
|
+
|
|
202
|
+
type SuccessData = {
|
|
203
|
+
message: string;
|
|
204
|
+
};
|
|
205
|
+
|
|
206
|
+
type ValiationError = {
|
|
207
|
+
name?: string;
|
|
208
|
+
};
|
|
209
|
+
|
|
210
|
+
const updateUserSchema = z.object({ name: z.string() });
|
|
211
|
+
|
|
212
|
+
export const updateUser = createFormAction<
|
|
213
|
+
SuccessData,
|
|
214
|
+
ErrorData,
|
|
215
|
+
ValiationError
|
|
216
|
+
>(({ success, failure, invalid }) =>
|
|
217
|
+
// success and failure helper functions create wrappers for success & error data respectively
|
|
218
|
+
async (prevState, formData) => {
|
|
219
|
+
if (prevState.type === "initial") {
|
|
220
|
+
// use the initialData passed to <Form /> here
|
|
221
|
+
// prevState.data === "foobar"
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
try {
|
|
225
|
+
const { name } = updateUserSchema.parse({
|
|
226
|
+
name: formData.get("name"),
|
|
227
|
+
});
|
|
228
|
+
|
|
229
|
+
const user = await updateCurrentUser(name);
|
|
230
|
+
|
|
231
|
+
if (user) {
|
|
232
|
+
// {type: "success", data: "Your profile has been updated.", error: null, validationError: null}
|
|
233
|
+
return success({
|
|
234
|
+
message: "Your profile has been updated.",
|
|
235
|
+
});
|
|
236
|
+
} else {
|
|
237
|
+
// {type: "error", data: null, error: { message: "No current user." }, validationError: null}
|
|
238
|
+
return failure({ message: "No current user." });
|
|
239
|
+
}
|
|
240
|
+
} catch (error) {
|
|
241
|
+
if (error instanceof ZodError) {
|
|
242
|
+
// {type: "invalid", data: null, error: null, validationError: {name: "Invalid input"}}
|
|
243
|
+
return invalid({
|
|
244
|
+
name: error.issues[0]?.message ?? "Validation error",
|
|
245
|
+
});
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
return failure({ message: "Failed to update user." });
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
);
|
|
252
|
+
```
|
|
253
|
+
|
|
254
|
+
The action creator supports arguments binding:
|
|
255
|
+
|
|
256
|
+
```ts
|
|
257
|
+
export const updateUser = createFormAction(
|
|
258
|
+
(
|
|
259
|
+
{ success, failure, invalid },
|
|
260
|
+
userId: string /* Here you can specify multiple arguments */
|
|
261
|
+
) =>
|
|
262
|
+
async (prevState, formData) => {
|
|
263
|
+
try {
|
|
264
|
+
const { name } = updateUserSchema.parse({
|
|
265
|
+
name: formData.get("name"),
|
|
266
|
+
});
|
|
267
|
+
|
|
268
|
+
const user = await db.users.findById(userId);
|
|
269
|
+
|
|
270
|
+
if (!user) {
|
|
271
|
+
return failure({ message: "No such user." });
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
const updated = await user.update({ name });
|
|
275
|
+
|
|
276
|
+
if (updated) {
|
|
277
|
+
return success({
|
|
278
|
+
message: "User has been updated.",
|
|
279
|
+
});
|
|
280
|
+
} else {
|
|
281
|
+
return failure({ message: "Failed to update." });
|
|
282
|
+
}
|
|
283
|
+
} catch (error) {
|
|
284
|
+
// handle error
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
);
|
|
288
|
+
|
|
289
|
+
// call bind as usuall, the "123" becomes the "userId"
|
|
290
|
+
updateUser.bind(null, "123");
|
|
291
|
+
```
|
|
292
|
+
|
|
293
|
+
### Action Context
|
|
294
|
+
|
|
295
|
+
The `<Action>` components enables you to access your `action`'s state with the `useActionContext()` hook:
|
|
296
|
+
|
|
297
|
+
```tsx
|
|
298
|
+
// 👉 Define standalone client form component (e.g. /app/auth/signup/SignUpForm.tsx)
|
|
299
|
+
"use client";
|
|
300
|
+
|
|
301
|
+
import { Action, Form, useActionContext } from "react-form-action/client";
|
|
302
|
+
import type { PropsWithChildren } from "react";
|
|
303
|
+
|
|
304
|
+
import { signupAction } from "./action";
|
|
305
|
+
|
|
306
|
+
function Pending({ children }: PropsWithChildren) {
|
|
307
|
+
// read any state from the ActionContext:
|
|
308
|
+
const {
|
|
309
|
+
error,
|
|
310
|
+
data,
|
|
311
|
+
validationError,
|
|
312
|
+
isPending,
|
|
313
|
+
isFailure,
|
|
314
|
+
isInvalid,
|
|
315
|
+
isSuccess,
|
|
316
|
+
isInitial,
|
|
317
|
+
} = useActionContext();
|
|
318
|
+
|
|
319
|
+
return isPending && children;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
// 💡 render this form on your RSC page (/app/auth/signup/page.tsx)
|
|
323
|
+
export function SignupForm() {
|
|
324
|
+
return (
|
|
325
|
+
<Action action={signupAction}>
|
|
326
|
+
<Form>
|
|
327
|
+
<input name="email" />
|
|
328
|
+
<input name="password" />
|
|
329
|
+
</Form>
|
|
330
|
+
{/* 🎆 Read the pending state outside the <Form> */}
|
|
331
|
+
<Pending>
|
|
332
|
+
{/* This renders only when the action is pending. 😎 */}
|
|
333
|
+
<p>Please wait...</p>
|
|
334
|
+
</Pending>
|
|
335
|
+
</Action>
|
|
336
|
+
);
|
|
337
|
+
}
|
|
338
|
+
```
|
|
339
|
+
|
|
340
|
+
### `<Form>` Component
|
|
341
|
+
|
|
342
|
+
The `<form>` submits the action in `onSubmit` handler to [prevent automatic form reset](https://github.com/facebook/react/issues/29034).
|
|
343
|
+
Pass `autoReset` prop to use the `action` prop instead and keep the default reset.
|
|
344
|
+
|
|
345
|
+
```tsx
|
|
346
|
+
"use client";
|
|
347
|
+
|
|
348
|
+
import { Action, Form } from "react-form-action/client";
|
|
349
|
+
|
|
350
|
+
import { updateUser } from "./action";
|
|
351
|
+
|
|
352
|
+
export function UpdateUserForm() {
|
|
353
|
+
return (
|
|
354
|
+
<Action action={updateUser}>
|
|
355
|
+
<Form autoReset>{/* ... */}</Form>
|
|
356
|
+
</Action>
|
|
357
|
+
);
|
|
358
|
+
}
|
|
359
|
+
```
|
|
360
|
+
|
|
361
|
+
### Context Bound Components `createComponents()`
|
|
362
|
+
|
|
363
|
+
Use the `createComponents(action)` helper to create components which use the ActionContext and have types bound to the action type.
|
|
364
|
+
|
|
365
|
+
#### `<FielError>` Component
|
|
366
|
+
|
|
367
|
+
```tsx
|
|
368
|
+
"use client";
|
|
369
|
+
|
|
370
|
+
// ⚠️ createComponents is usable only in "use client" components
|
|
371
|
+
import { Form, createComponents } from "react-form-action/client";
|
|
372
|
+
|
|
373
|
+
import { authAction } from "./actions";
|
|
374
|
+
|
|
375
|
+
export const signUpAction = authAction
|
|
376
|
+
.input(
|
|
377
|
+
z
|
|
378
|
+
.object({
|
|
379
|
+
user: z.object({
|
|
380
|
+
email: z.string().email(),
|
|
381
|
+
name: z.string(),
|
|
382
|
+
}),
|
|
383
|
+
password: z.string().min(8),
|
|
384
|
+
confirm: z.string(),
|
|
385
|
+
})
|
|
386
|
+
.refine((data) => data.password === data.confirm, {
|
|
387
|
+
message: "Passwords don't match",
|
|
388
|
+
})
|
|
389
|
+
)
|
|
390
|
+
.run(async ({ ctx, input }) => {
|
|
391
|
+
return null;
|
|
392
|
+
});
|
|
393
|
+
|
|
394
|
+
// 🌟 The FieldError is now bound do the signUpAction input schema which allows autocompletion for its "name" prop
|
|
395
|
+
// ⚠️ Usable only with actions created with the formAction builder
|
|
396
|
+
const { FieldError } = createComponents(signUpAction);
|
|
397
|
+
|
|
398
|
+
export function SignUpForm() {
|
|
399
|
+
return (
|
|
400
|
+
<Action action={signUpAction} initialData={null}>
|
|
401
|
+
<Form>
|
|
402
|
+
{/* 1️⃣ When the "name" prop is ommited, the top-level error will be rendered e.g.:
|
|
403
|
+
"Passwords don't match" */}
|
|
404
|
+
<FieldError />
|
|
405
|
+
{/* 2️⃣ Access fields by their name: */}
|
|
406
|
+
<FieldError name="password" />
|
|
407
|
+
{/* 3️⃣ Access nested fields by dot access notation: */}
|
|
408
|
+
<FieldError name="user.email" />
|
|
409
|
+
</Form>
|
|
410
|
+
</Action>
|
|
411
|
+
);
|
|
412
|
+
}
|
|
413
|
+
```
|
|
414
|
+
|
|
415
|
+
#### `<Success>`
|
|
416
|
+
|
|
417
|
+
#### When children are JSX
|
|
418
|
+
|
|
419
|
+
```tsx
|
|
420
|
+
import { Action, createComponents } from "react-form-action/client";
|
|
421
|
+
|
|
422
|
+
const { Success } = createComponents(signUpAction);
|
|
423
|
+
|
|
424
|
+
function MyForm() {
|
|
425
|
+
return (
|
|
426
|
+
<Action action={signUpAction}>
|
|
427
|
+
<Success>
|
|
428
|
+
{/* 👉 The message will render only after the action has succeeded */}
|
|
429
|
+
<p>You've been signed up!</p>
|
|
430
|
+
</Success>
|
|
431
|
+
</Action>
|
|
432
|
+
);
|
|
433
|
+
}
|
|
434
|
+
```
|
|
435
|
+
|
|
436
|
+
#### When children is a render prop
|
|
437
|
+
|
|
438
|
+
```tsx
|
|
439
|
+
import { createComponents } from "react-form-action/client";
|
|
440
|
+
|
|
441
|
+
const { Success } = createComponents(signUpAction);
|
|
442
|
+
|
|
443
|
+
function Label({children}: PropsWithChildren) {
|
|
444
|
+
return (
|
|
445
|
+
<Success>
|
|
446
|
+
{({ isSuccess, data }) => (
|
|
447
|
+
{/* 👉 With a render prop, the children are always mounted, regardles of the isSuccess flag */}
|
|
448
|
+
<label className={isSuccess ? "green" : ""}>
|
|
449
|
+
{children}
|
|
450
|
+
</label>
|
|
451
|
+
)}
|
|
452
|
+
</Success>
|
|
453
|
+
);
|
|
454
|
+
};
|
|
455
|
+
```
|
|
456
|
+
|
|
457
|
+
### `<Pending>`
|
|
458
|
+
|
|
459
|
+
Render children when the action is pending:
|
|
460
|
+
|
|
461
|
+
#### When children are JSX
|
|
462
|
+
|
|
463
|
+
```tsx
|
|
464
|
+
import { Action, Pending } from "react-form-action/client";
|
|
465
|
+
|
|
466
|
+
import { Spinner } from "./components";
|
|
467
|
+
|
|
468
|
+
function MyForm() {
|
|
469
|
+
return (
|
|
470
|
+
<Action action={action}>
|
|
471
|
+
{/* 👉 Unlike the React.useFormStatus() hook, we don't need here the <form> element at all. */}
|
|
472
|
+
<Pending>
|
|
473
|
+
{/* 👉 The spinner will UNMOUNT when the action is NOT pending */}
|
|
474
|
+
<Spinner />
|
|
475
|
+
</Pending>
|
|
476
|
+
</Action>
|
|
477
|
+
);
|
|
478
|
+
}
|
|
479
|
+
```
|
|
480
|
+
|
|
481
|
+
#### When children is a render prop
|
|
482
|
+
|
|
483
|
+
```tsx
|
|
484
|
+
import { Pending } from "react-form-action/client";
|
|
485
|
+
|
|
486
|
+
function SubmitButton() {
|
|
487
|
+
return (
|
|
488
|
+
<Pending>
|
|
489
|
+
{({ isPending }) => (
|
|
490
|
+
{/* 👉 With a render prop, the children are always mounted, regardles of the isPending flag */}
|
|
491
|
+
<button type="submit" disabled={isPending}>
|
|
492
|
+
{isPending ? "Submitting..." : "Submit"}
|
|
493
|
+
</button>
|
|
494
|
+
)}
|
|
495
|
+
</Pending>
|
|
496
|
+
);
|
|
497
|
+
};
|
|
498
|
+
```
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function u(a){return{type:"initial",data:a,error:null,validationError:null}}function d(a){function t(r){return{type:"success",data:r,error:null,validationError:null}}function o(r){return{type:"failure",data:null,error:r,validationError:null}}function n(r){return{type:"invalid",data:null,error:null,validationError:r}}return(...r)=>{let e=r.pop(),i=r.pop(),l=[...r];return a({success:t,failure:o,invalid:n},...l)(i,e)}}export{u as a,d as b};
|
package/dist/client.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use client";import{a as m}from"./chunk-
|
|
1
|
+
"use client";import{a as m}from"./chunk-LPB4R2UB.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(o){let t=S(u);if(!t)throw new Error("ActionContext must be initialized before use. Is your useActionContext hook wrapped with an <Action> Component?");return t}function I({children:o,action:t,initialData:i,permalink:e}){let[r,n,s]=F(t,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},o)}import A,{startTransition as C}from"react";function V({autoReset:o=!1,...t}){let{action:i}=a();return A.createElement("form",{...o?{action:i}:{onSubmit:r=>{r.preventDefault();let n=r.currentTarget;C(()=>{i(new FormData(n))})}},...t})}import c from"react";import f from"react";var h=".",d=Object.freeze({_errors:Object.freeze([])});function E({errors:o,name:t,children:i=({error:e})=>f.createElement(f.Fragment,null,e)}){if(t.length===0)return i({name:t,error:o._errors[0],errors:o._errors});let e=t.split(h),r=o;for(;e.length;){let n=e.shift();r=r[n]??d}return i({name:t,error:r._errors[0],errors:r._errors})}function $(o){function t({name:e,children:r}){let{isInvalid:n,validationError:s}=a(o);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(o);return typeof e=="function"?e(r?{isSuccess:r,data:n}:{isSuccess:r,data:n}):r&&e}return{FieldError:t,Success:i}}function X({children:o}){let{isPending:t}=a();return typeof o=="function"?o({isPending:t}):t&&o}export{I as Action,V as Form,X as Pending,E as ZodFieldError,$ as createComponents,d as noError,a as useActionContext};
|
package/dist/index.d.mts
CHANGED
|
@@ -34,7 +34,7 @@ type FormActionBuilder<Schema extends ZodTypeAny | EmptyInput, Err = Error, Cont
|
|
|
34
34
|
* @param action async function to execute. It will receive parsed formData as input, when the builder was initialized with a schema.
|
|
35
35
|
* @returns runnable server action exportable from a module.
|
|
36
36
|
*/
|
|
37
|
-
run: Schema extends ZodTypeAny ? <Data>(action: SchemaAction<Data, Context
|
|
37
|
+
run: Schema extends ZodTypeAny ? <Data>(action: SchemaAction<Data, Flatten<Context>, Schema>) => (state: ActionState<Data, Err, z.inferFormattedError<Schema>>, payload: FormData) => Promise<Flatten<InvalidState<z.inferFormattedError<Schema>> | FailureState<Err> | SuccessState<Data>>> : <Data>(action: Action<Data, Flatten<Context>>) => (state: ActionState<Data, Err>, payload: FormData) => Promise<Flatten<FailureState<Err> | SuccessState<Data>>>;
|
|
38
38
|
/**
|
|
39
39
|
* A chainable context enhancing helper.
|
|
40
40
|
* @param middleware A function which receives the current context, and returns an object which will be added to the context.
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as A,b as p}from"./chunk-
|
|
1
|
+
import{a as A,b as p}from"./chunk-LPB4R2UB.mjs";import{ZodFirstPartyTypeKind as E}from"zod";import{zfd as C}from"zod-form-data";var d=Symbol();function i(r,o=[],n){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(r===d)return i(t,o,n);if(r._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(r._def.typeName===E.ZodObject){let e=r.merge(t);return i(e,o)}else throw Error("Merging inputs works only for object schemas without effects.")},use(t){return i(r,[...o,t],n)},error(t){return i(r,o,t)},run:r===d?t=>p(({success:e,failure:a})=>async(s,m)=>{let x=await f(m);try{return e(await t({ctx:x}))}catch(c){if(n)return a(await n({error:c,ctx:x}));throw c}}):r===d?void 0:t=>p(({success:e,failure:a,invalid:s})=>{let m=C.formData(r);return async(x,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(n)return a(await n({error:S,ctx:y}));throw S}}})}}var P=i(d);export{p as createFormAction,P as formAction,A as initial};
|
package/package.json
CHANGED
package/dist/chunk-22TNX3DL.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
function d(a){return{type:"initial",data:a,error:null,validationError:null}}function u(a){function t(r){return{type:"success",data:r,error:null,validationError:null}}function o(r){return{type:"failure",data:null,error:r,validationError:null}}function e(r){return{type:"invalid",data:null,error:null,validationError:r}}return(...r)=>{let[n,i,...l]=r.reverse();return a({success:t,failure:o,invalid:e},...l)(i,n)}}export{d as a,u as b};
|