import * as React from 'react'; import { createRoot } from 'react-dom/client'; import { useForm } from '@tanstack/react-form'; import { z } from 'zod'; import { FieldError } from './field-error'; import './index.css'; interface Role { external: External; name: string; } interface Person { name: string; age: number; roles: Record; } enum External { True = 'true', False = 'false', } const defaultPerson: Person = { name: 'John Doe', age: 30, roles: { Admin: { name: 'Admin', external: External.False, }, User: { name: 'User', external: External.False, }, }, }; const roles: Record = { Admin: { name: 'Admin', external: External.False, }, User: { name: 'User', external: External.False, }, }; function App() { const form = useForm({ defaultValues: defaultPerson, onSubmit({ value }) { alert(JSON.stringify(value)); }, }); return (
{ e.preventDefault(); e.stopPropagation(); form.handleSubmit(); }} > {(field) => { return ( <> {Object.entries(roles).map(([roleName, role], idx) => ( {(subField) => (
{ const currentFieldValue = field.state.value; console.log(currentFieldValue, role.name, role); if (event.target.checked) { const newValue = { ...currentFieldValue, [role.name]: role, } console.log(newValue) field.setValue(newValue); } else { const newValue = Object.fromEntries( Object.entries(currentFieldValue).filter( ([key]) => key !== role.name ) ); console.log(newValue); field.setValue(newValue); } }} value={role.name} />
)}
))} ); }}
[state.canSubmit, state.isSubmitting]} children={([canSubmit, isSubmitting]) => ( )} /> state.values}> {(values) => ( <>
                {JSON.stringify(values, null, 4)}
              
)}
); } const rootElement = document.getElementById('root')!; createRoot(rootElement).render( );