|
| 1 | +'use client'; |
| 2 | + |
| 3 | +import { useEffect } from 'react'; |
| 4 | +import type { FormAction } from 'soybean-react-ui'; |
| 5 | +import { Button, Card, Form, FormField, Input, useForm } from 'soybean-react-ui'; |
| 6 | + |
| 7 | +// ============ Analytics Middleware (logging/tracking) ============ |
| 8 | +function analyticsMiddleware({ getState }: { dispatch: (a: FormAction) => void; getState: () => any }) { |
| 9 | + return (next: (a: FormAction) => void) => (action: FormAction) => { |
| 10 | + // the action before the middleware |
| 11 | + console.log('[middleware] before', action, 'state:', getState()); |
| 12 | + |
| 13 | + next(action); // run default logic first |
| 14 | + |
| 15 | + // the action after the middleware |
| 16 | + console.log('[middleware] after', action, 'state:', getState()); |
| 17 | + |
| 18 | + if (action.type === 'setFieldValue') { |
| 19 | + console.log(`[Analytics] User modified field: ${action.name}`, action.value); |
| 20 | + // Report tracking event |
| 21 | + // report({ field: action.name, value: action.value }); |
| 22 | + } |
| 23 | + }; |
| 24 | +} |
| 25 | + |
| 26 | +// ============ Form field types ============ |
| 27 | +type Inputs = { |
| 28 | + confirmPassword: string; |
| 29 | + password: string; |
| 30 | + username: string; |
| 31 | +}; |
| 32 | + |
| 33 | +const initialValues: Inputs = { |
| 34 | + confirmPassword: '123456', |
| 35 | + password: '123456', |
| 36 | + username: 'ohh' |
| 37 | +}; |
| 38 | + |
| 39 | +const UseFormWithMiddleware = () => { |
| 40 | + const [form] = useForm<Inputs>(); |
| 41 | + |
| 42 | + useEffect(() => { |
| 43 | + // Register middleware: add analytics/tracing for form actions |
| 44 | + form.use(analyticsMiddleware); |
| 45 | + }, []); |
| 46 | + |
| 47 | + return ( |
| 48 | + <Card title="UseForm with Middleware (Sync Password)"> |
| 49 | + <Form |
| 50 | + className="w-[480px] max-sm:w-full space-y-4" |
| 51 | + form={form} |
| 52 | + initialValues={initialValues} |
| 53 | + > |
| 54 | + <FormField |
| 55 | + label="Username" |
| 56 | + name="username" |
| 57 | + > |
| 58 | + <Input /> |
| 59 | + </FormField> |
| 60 | + |
| 61 | + <FormField |
| 62 | + label="Password" |
| 63 | + name="password" |
| 64 | + > |
| 65 | + <Input /> |
| 66 | + </FormField> |
| 67 | + |
| 68 | + <FormField |
| 69 | + label="Confirm Password" |
| 70 | + name="confirmPassword" |
| 71 | + > |
| 72 | + <Input /> |
| 73 | + </FormField> |
| 74 | + |
| 75 | + <div className="flex gap-2 flex-wrap"> |
| 76 | + <Button type="submit">Submit</Button> |
| 77 | + <Button onClick={() => form.setFieldValue('username', 'ohh-889')}>Set Username</Button> |
| 78 | + </div> |
| 79 | + </Form> |
| 80 | + </Card> |
| 81 | + ); |
| 82 | +}; |
| 83 | + |
| 84 | +export default UseFormWithMiddleware; |
0 commit comments