Skip to content

Commit 3a9cbfb

Browse files
committed
Updates
1 parent d864d41 commit 3a9cbfb

File tree

1 file changed

+70
-1
lines changed

1 file changed

+70
-1
lines changed

README.md

Lines changed: 70 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ Then we create a onSubmit form handler that will call our validators.
7575
const handleSubmit = (event) => {
7676
event.preventDefault();
7777

78-
if (!form.isValid()) {
78+
if (!form.validate()) {
7979
// form is invalid, exit early
8080
// when this happens, our hook will update the fields that failed validation
8181
return;
@@ -107,3 +107,72 @@ As you may notice, for every given property in your schema, our hook will create
107107
<button type="submit">Submit</button>
108108
</form>
109109
```
110+
111+
## Forms with nested objects
112+
113+
Say that you have a nested object that you would want to send to your API
114+
115+
```js
116+
const object = { foo: { bar: { baz: 'hi' } } };
117+
```
118+
119+
```js
120+
const form: any = useForm(
121+
{
122+
foo: { bar: { baz: '' } },
123+
},
124+
{
125+
type: 'object',
126+
properties: {
127+
foo: {
128+
type: 'object',
129+
properties: {
130+
bar: {
131+
type: 'object',
132+
required: ['baz'],
133+
properties: {
134+
baz: {
135+
type: 'string',
136+
minLength: 5,
137+
errorMessage: {
138+
minLength: 'Too short',
139+
},
140+
},
141+
},
142+
},
143+
},
144+
},
145+
},
146+
},
147+
);
148+
```
149+
150+
Normally, with most libraries out there, you would always get a flat object back, then you would have to "normalize" it before it's sent somewhere.
151+
152+
With this library, that's a lot easier.
153+
154+
Let's imagine that we have our own custom input
155+
156+
```jsx
157+
const CustomInput = ({ form, name }) => {
158+
return (
159+
<>
160+
<input
161+
type="text"
162+
name={name}
163+
value={form.state[name].value}
164+
onChange={(e) => form.setState({ [e.target.name]: e.target.value })}
165+
/>
166+
{form.state[name].error && <p>{form.state[name].error}</p>}
167+
</>
168+
);
169+
};
170+
```
171+
172+
```jsx
173+
<CustomInput form={form} name="foo.bar.baz" />
174+
```
175+
176+
Simply pass the object path as the `name` prop and this library will generate the object for you. But not only that, validate it against the provided schema.
177+
178+
The fact that we `unflatten` the state makes it incredibly easy to make your form generate the exact object shape that you want, instead of needing to do it manually yourself.

0 commit comments

Comments
 (0)