Skip to content

Commit 4219db0

Browse files
authored
Merge pull request #20 from Programmer-Network/book/fix-set-error-issue
fix: avoid clearing old state when setting errors
2 parents 09f9927 + 226971c commit 4219db0

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

src/index.ts

+1
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,7 @@ const useAJVForm = <T extends Record<string, any>>(
181181
setState((prevState) =>
182182
Object.keys(newErrors).reduce((updatedState, fieldName) => {
183183
return {
184+
...prevState,
184185
...updatedState,
185186
[fieldName]: {
186187
...prevState[fieldName],

src/useAjvForm.test.tsx

+38
Original file line numberDiff line numberDiff line change
@@ -586,6 +586,44 @@ describe('useAJVForm should properly set errors programmatically using setErrors
586586
expect(result.current.state.description.error).toBe('Monkey message');
587587
});
588588

589+
it('sets the errors using form.setErrors without affecting other state', () => {
590+
const initialData = { title: 'Foo', description: 'Bar' };
591+
const schema: JSONSchemaType<{ title: string; description: string }> = {
592+
type: 'object',
593+
required: ['title', 'description'],
594+
properties: {
595+
title: { type: 'string' },
596+
description: { type: 'string' },
597+
},
598+
};
599+
600+
const { result } = renderHook(() =>
601+
useAJVForm(
602+
initialData,
603+
schema,
604+
{
605+
userDefinedMessages: {
606+
required: () => 'Monkey message',
607+
},
608+
},
609+
),
610+
);
611+
612+
result.current.setErrors([
613+
{
614+
instancePath: '/description',
615+
keyword: 'required',
616+
params: { missingProperty: 'description' },
617+
schemaPath: '#/required',
618+
},
619+
]);
620+
621+
expect(result.current.state.title.value).toBe('Foo');
622+
expect(result.current.state.description.value).toBe('Bar');
623+
624+
expect(result.current.state.description.error).toBe('Monkey message');
625+
});
626+
589627
it('should handle conditional validations on locationType correctly', () => {
590628
/**
591629
* Test Scenario:

0 commit comments

Comments
 (0)