diff --git a/src/__tests__/useController.test.tsx b/src/__tests__/useController.test.tsx index 2fe6803b79c..8c03f349505 100644 --- a/src/__tests__/useController.test.tsx +++ b/src/__tests__/useController.test.tsx @@ -1,4 +1,4 @@ -import React from 'react'; +import React, { useState } from 'react'; import { fireEvent, render, screen, waitFor } from '@testing-library/react'; import { Controller } from '../controller'; @@ -6,6 +6,7 @@ import { Control, FieldPath, FieldValues } from '../types'; import { useController } from '../useController'; import { useForm } from '../useForm'; import { FormProvider, useFormContext } from '../useFormContext'; +import isBoolean from '../utils/isBoolean'; describe('useController', () => { it('should render input correctly', () => { @@ -875,4 +876,77 @@ describe('useController', () => { expect(callback).toBeCalled(); }); }); + + it('should not omit form value when disabled is not been presented', async () => { + const onSubmit = jest.fn(); + + const App = () => { + const { handleSubmit, control } = useForm({ + defaultValues: { + test: 'test', + }, + }); + const [toggle, setToggle] = useState(undefined); + const { field } = useController({ + control, + name: 'test', + disabled: toggle, + }); + + return ( +
{ + onSubmit(data); + })} + > + + + +
+ ); + }; + + render(); + + fireEvent.click(screen.getByRole('button', { name: 'submit' })); + + await waitFor(() => + expect(onSubmit).toBeCalledWith({ + test: 'test', + }), + ); + + fireEvent.click(screen.getByRole('button', { name: 'toggle' })); + + fireEvent.click(screen.getByRole('button', { name: 'submit' })); + + await waitFor(() => + expect(onSubmit).toBeCalledWith({ + test: 'test', + }), + ); + + fireEvent.click(screen.getByRole('button', { name: 'toggle' })); + + fireEvent.click(screen.getByRole('button', { name: 'submit' })); + + await waitFor(() => + expect(onSubmit).toBeCalledWith({ + test: undefined, + }), + ); + }); }); diff --git a/src/useController.ts b/src/useController.ts index 50fff5b3881..cd5549e8876 100644 --- a/src/useController.ts +++ b/src/useController.ts @@ -74,12 +74,10 @@ export function useController< control.register(name, { ...props.rules, value, - disabled: props.disabled, + ...(isBoolean(props.disabled) ? { disabled: props.disabled } : {}), }), ); - _registerProps.current = control.register(name, props.rules); - React.useEffect(() => { const _shouldUnregisterField = control._options.shouldUnregister || shouldUnregister;