Skip to content

Commit 0e10f3e

Browse files
committed
Extend useForm with plain data object
1 parent 25eed4f commit 0e10f3e

File tree

4 files changed

+38
-1
lines changed

4 files changed

+38
-1
lines changed

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@programmer_network/use-ajv-form",
3-
"version": "1.0.8",
3+
"version": "1.0.9",
44
"description": "Custom React Hook that integrates with Ajv JSON Schema Validator",
55
"main": "dist/use-ajv-form.es.js",
66
"author": "Aleksandar Grbic",

src/index.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,12 @@ const useAJVForm = <T extends Record<string, any>>(
187187
onBlur: handleBlur,
188188
isValid,
189189
isDirty,
190+
data: Object.keys(state).reduce((acc, fieldName) => {
191+
return {
192+
...acc,
193+
[fieldName]: getValue(state[fieldName].value),
194+
};
195+
}, {} as T),
190196
state,
191197
};
192198
};

src/useAjvForm.test.tsx

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -336,4 +336,34 @@ describe('useAJVForm', () => {
336336

337337
expect(result.current.isValid).toBe(false);
338338
});
339+
340+
it('should correctly set data object', () => {
341+
const initialData = { title: '', description: '' };
342+
const schema: JSONSchemaType<{ title: string; description: string }> = {
343+
type: 'object',
344+
required: ['title'],
345+
properties: {
346+
title: { type: 'string' },
347+
description: { type: 'string' },
348+
},
349+
};
350+
351+
const { result } = renderHook(() => useAJVForm(initialData, schema));
352+
353+
result.current.validate();
354+
355+
result.current.set({ title: 'Hello' });
356+
result.current.onBlur('title');
357+
358+
expect(result.current.data).toEqual({ title: 'Hello', description: '' });
359+
expect(result.current.isValid).toBe(true);
360+
361+
result.current.set({ title: '112' });
362+
result.current.set({ description: 'John Doe' });
363+
result.current.onBlur('title');
364+
365+
expect(result.current.data).toEqual({ title: '112', description: 'John Doe' });
366+
367+
expect(result.current.isValid).toBe(true);
368+
});
339369
});

src/utils/types.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ export type useFormErrors<T> = {
5454
[K in keyof T]?: string;
5555
};
5656
export interface UseFormReturn<T> {
57+
data: T;
5758
state: IState<T>;
5859
set: (form: Partial<{ [K in keyof T]: T[K] }>) => void;
5960
reset: () => void;

0 commit comments

Comments
 (0)