Skip to content

Commit c5489c1

Browse files
committed
Fix issue when introducing new field
1 parent 71b6470 commit c5489c1

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

src/index.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -193,7 +193,7 @@ const useAJVForm = <T extends Record<string, any>>(
193193

194194
const isDirty = useMemo(() => {
195195
return Object.keys(state).some(
196-
(key) => state[key].value !== initialStateRef.current[key].value,
196+
(key) => state[key].value !== initialStateRef.current[key]?.value,
197197
);
198198
}, [state]);
199199

src/useAjvForm.test.tsx

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,39 @@ describe('useAJVForm', () => {
5252
expect(result.current.state.title.value).toBe('New Title');
5353
});
5454

55+
it('handles onChange with fields not in initial data', () => {
56+
const initialData = { name: '' };
57+
const schema: JSONSchemaType<{ name: string }> = {
58+
type: 'object',
59+
required: ['name'],
60+
properties: {
61+
name: {
62+
type: 'string',
63+
minLength: 1,
64+
maxLength: 65,
65+
errorMessage: {
66+
maxLength: 'Name cannot be greater than 65 characters.',
67+
},
68+
},
69+
},
70+
};
71+
72+
const { result } = renderHook(() => useAJVForm(initialData, schema));
73+
74+
// Accidentally including an additional field in update
75+
const payload = { name: 'Dog', id: 1 };
76+
result.current.set(payload);
77+
78+
expect(result.current.state.name.value).toBe('Dog');
79+
expect(result.current.isDirty).toBeTruthy();
80+
81+
// Clearing existing field has earlier caused hook to throw
82+
result.current.set({ name: '' });
83+
84+
expect(result.current.state.name.value).toBe('');
85+
expect(result.current.isDirty).toBeTruthy();
86+
});
87+
5588
it('handles onBlur event with validation correctly', () => {
5689
const initialData = { title: '' };
5790
const schema: JSONSchemaType<{ title: string }> = {

0 commit comments

Comments
 (0)