Skip to content

Commit

Permalink
🐞 fix react-hook-form#11276 issue with disabled omit on Controller (r…
Browse files Browse the repository at this point in the history
  • Loading branch information
bluebill1049 authored and rafaelcalhau committed May 5, 2024
1 parent 664a635 commit 88c8168
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 4 deletions.
76 changes: 75 additions & 1 deletion src/__tests__/useController.test.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import React from 'react';
import React, { useState } from 'react';
import { fireEvent, render, screen, waitFor } from '@testing-library/react';

import { Controller } from '../controller';
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', () => {
Expand Down Expand Up @@ -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<boolean | undefined>(undefined);
const { field } = useController({
control,
name: 'test',
disabled: toggle,
});

return (
<form
onSubmit={handleSubmit((data) => {
onSubmit(data);
})}
>
<input {...field} />
<button>submit</button>
<button
type={'button'}
onClick={() => {
setToggle((value) => {
if (isBoolean(value)) {
return false;
}

return !value;
});
}}
>
toggle
</button>
</form>
);
};

render(<App />);

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,
}),
);
});
});
4 changes: 1 addition & 3 deletions src/useController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down

0 comments on commit 88c8168

Please sign in to comment.