Skip to content

Commit

Permalink
Keep errors and other state on ArrayInput unmount
Browse files Browse the repository at this point in the history
  • Loading branch information
sweco-sedalh committed Feb 26, 2024
1 parent 5e2ed7d commit ffa6c95
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 1 deletion.
54 changes: 54 additions & 0 deletions packages/ra-ui-materialui/src/input/ArrayInput/ArrayInput.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,60 @@ describe('<ArrayInput />', () => {
});
});

it('should not clear errors of children when unmounted', async () => {
let setArrayInputVisible;

const MyArrayInput = () => {
const [visible, setVisible] = React.useState(true);

setArrayInputVisible = setVisible;

return visible ? (
<ArrayInput resource="bar" source="arr">
<SimpleFormIterator>
<TextInput source="id" />
<TextInput source="foo" />
</SimpleFormIterator>
</ArrayInput>
) : null;
};

render(
<AdminContext dataProvider={testDataProvider()}>
<SimpleForm
onSubmit={jest.fn}
defaultValues={{
arr: [
{ id: 1, foo: 'bar' },
{ id: 2, foo: 'baz' },
],
}}
validate={() => ({ arr: [{ foo: 'Must be "baz"' }, {}] })}
>
<MyArrayInput />
</SimpleForm>
</AdminContext>
);

// change one input to enable the SaveButton (which is disabled when the form is pristine)
fireEvent.change(
screen.getAllByLabelText('resources.bar.fields.arr.id')[0],
{
target: { value: '42' },
}
);
fireEvent.click(await screen.findByLabelText('ra.action.save'));

await screen.findByText('Must be "baz"');

setArrayInputVisible(false);
expect(screen.queryByText('Must be "baz"')).toBeNull();

// ensure errors are still there after re-mount
setArrayInputVisible(true);
await screen.findByText('Must be "baz"');
});

it('should allow to have a helperText', () => {
render(
<AdminContext dataProvider={testDataProvider()}>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,12 @@ export const ArrayInput = (props: ArrayInputProps) => {
formGroups.registerField(source, formGroupName);

return () => {
unregister(source, { keepValue: true });
unregister(source, {
keepValue: true,
keepError: true,
keepDirty: true,
keepTouched: true,
});
formGroups.unregisterField(source, formGroupName);
};
}, [register, unregister, source, formGroups, formGroupName]);
Expand Down

0 comments on commit ffa6c95

Please sign in to comment.