Skip to content

Commit

Permalink
馃悶 fix #5229 issue with ref become undefined (#5233)
Browse files Browse the repository at this point in the history
  • Loading branch information
bluebill1049 committed May 18, 2021
1 parent d50c330 commit 00df238
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
39 changes: 39 additions & 0 deletions src/__tests__/controller.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -995,4 +995,43 @@ describe('Controller', () => {

expect(watchedValue).toMatchSnapshot();
});

it('should set ref to empty object when ref is not defined', () => {
const App = () => {
const [show, setShow] = React.useState(false);
const { control } = useForm({
mode: 'onChange',
defaultValues: {
test: {
firstName: '',
lastName: '',
},
},
});

return (
<div>
{show && (
<Controller
name={'test'}
rules={{ required: true }}
control={control}
render={({ field }) => (
<input value={field.value as any} onChange={field.onChange} />
)}
/>
)}
<button onClick={() => setShow(!show)}>setShow</button>
</div>
);
};

render(<App />);

fireEvent.click(screen.getByRole('button'));

fireEvent.change(screen.getByRole('textbox'), {
target: { value: 'test' },
});
});
});
2 changes: 1 addition & 1 deletion src/useForm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -968,7 +968,7 @@ export function useForm<
...(isInitialRegister
? { ref: { name } }
: {
ref: (get(fieldsRef.current, name)._f || {}).ref,
ref: (get(fieldsRef.current, name)._f || {}).ref || {},
...get(fieldsRef.current, name)._f,
}),
name,
Expand Down

0 comments on commit 00df238

Please sign in to comment.