Skip to content

Commit

Permalink
fix(Form): remove error state when input is disabled (#1057)
Browse files Browse the repository at this point in the history
https://jira.tid.es/browse/WEB-1770

---------

Co-authored-by: Pedro Ladaria <[email protected]>
  • Loading branch information
pladaria and Pedro Ladaria authored Mar 26, 2024
1 parent 3ce0fac commit 82f1938
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 3 deletions.
48 changes: 47 additions & 1 deletion src/__tests__/form-test.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as React from 'react';
import {render, screen, waitFor} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {ButtonPrimary, Form, TextField, EmailField, PasswordField} from '..';
import {ButtonPrimary, Form, TextField, EmailField, PasswordField, Switch, PhoneNumberField} from '..';
import ThemeContextProvider from '../theme-context-provider';
import {makeTheme} from './test-utils';

Expand Down Expand Up @@ -227,3 +227,49 @@ test('can listen to form validation errors', async () => {
surname: 'Este campo es obligatorio',
});
});

test('Disabling a field removes the error state and disabled fields are not submitted', async () => {
const submitSpy = jest.fn();

const MyComponent = () => {
const [isEmailSelected, setIsEmailSelected] = React.useState(true);
return (
<ThemeContextProvider theme={makeTheme()}>
<Form onSubmit={submitSpy}>
<PhoneNumberField disabled={isEmailSelected} name="phone" label="Phone" />
<EmailField disabled={!isEmailSelected} name="email" label="Email" />
<Switch
name="switch"
checked={isEmailSelected}
onChange={() => setIsEmailSelected(!isEmailSelected)}
/>
<ButtonPrimary submit>Submit</ButtonPrimary>
</Form>
</ThemeContextProvider>
);
};

render(<MyComponent />);

const submitButton = await screen.findByRole('button', {name: 'Submit'});
const emailField = await screen.findByLabelText('Email');
const phoneField = await screen.findByLabelText('Phone');

await userEvent.type(emailField, 'bad-email');
await userEvent.click(submitButton);

await screen.findByText('Email incorrecto');
expect(submitSpy).not.toHaveBeenCalled();

await userEvent.click(screen.getByRole('switch'));
expect(emailField).toBeDisabled();
expect(screen.queryByText('Email incorrecto')).not.toBeInTheDocument();

await userEvent.type(phoneField, '654834455');
await userEvent.click(submitButton);

expect(submitSpy).toHaveBeenCalledWith(
{phone: '654834455', switch: false},
{phone: '654 83 44 55', switch: false}
);
});
6 changes: 6 additions & 0 deletions src/form-context.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,12 @@ export const useFieldProps = ({
setValue({name, value: processValueRef.current(rawValue)});
}, [name, rawValue, setRawValue, setValue]);

React.useEffect(() => {
if (disabled) {
setFormError({name, error: undefined});
}
}, [disabled, name, setFormError]);

return {
value,
defaultValue: defaultValue ?? (value === undefined ? rawValues[name] ?? '' : undefined),
Expand Down
7 changes: 5 additions & 2 deletions src/form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,11 @@ const Form: React.FC<FormProps> = ({
[]
);

const setFormError = ({name, error}: {name: string; error?: string}) =>
setFormErrors((formErrors) => ({...formErrors, [name]: error}));
const setFormError = React.useCallback(
({name, error}: {name: string; error?: string}) =>
setFormErrors((formErrors) => ({...formErrors, [name]: error})),
[]
);

/**
* returns true if all fields are ok and focuses the first field with an error
Expand Down

1 comment on commit 82f1938

@github-actions
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Deploy preview for mistica-web ready!

✅ Preview
https://mistica-nvbmdfde5-tuentisre.vercel.app

Built with commit 82f1938.
This pull request is being automatically deployed with vercel-action

Please sign in to comment.