Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix FormDataConsumer's values not being up-to-date on mount #8340

Merged
merged 9 commits into from
Nov 17, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
120 changes: 118 additions & 2 deletions packages/ra-core/src/form/FormDataConsumer.spec.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,17 @@
import * as React from 'react';
import { render } from '@testing-library/react';
import { render, waitFor, screen, fireEvent } from '@testing-library/react';

import { FormDataConsumerView } from './FormDataConsumer';
import FormDataConsumer, { FormDataConsumerView } from './FormDataConsumer';
import { testDataProvider } from '../dataProvider';
import {
AdminContext,
BooleanInput,
SimpleForm,
TextInput,
SimpleFormIterator,
ArrayInput,
} from 'ra-ui-materialui';
import expect from 'expect';

describe('FormDataConsumerView', () => {
it('does not call its children function with scopedFormData and getSource if it did not receive an index prop', () => {
Expand All @@ -26,6 +36,7 @@ describe('FormDataConsumerView', () => {
it('calls its children function with scopedFormData and getSource if it received an index prop', () => {
const children = jest.fn(({ getSource }) => {
getSource('id');
return null;
});
const formData = { id: 123, title: 'A title', authors: [{ id: 0 }] };

Expand All @@ -46,4 +57,109 @@ describe('FormDataConsumerView', () => {
'authors[0].id'
);
});

it('calls its children with updated formData on first render', async () => {
let globalFormData;
render(
<AdminContext dataProvider={testDataProvider()}>
<SimpleForm>
<BooleanInput source="hi" defaultValue />
<FormDataConsumer>
{({ formData, ...rest }) => {
globalFormData = formData;

return <TextInput source="bye" {...rest} />;
}}
</FormDataConsumer>
</SimpleForm>
</AdminContext>
);

await waitFor(() => {
expect(globalFormData).toEqual({ hi: true, bye: undefined });
});
});

it('should be reactive', async () => {
render(
<AdminContext dataProvider={testDataProvider()}>
<SimpleForm>
<BooleanInput source="hi" defaultValue />
<FormDataConsumer>
{({ formData, ...rest }) =>
!formData.hi ? (
<TextInput source="bye" {...rest} />
) : null
}
</FormDataConsumer>
</SimpleForm>
</AdminContext>
);

await waitFor(() => {
expect(
screen.queryByLabelText('resources.undefined.fields.bye')
).toBeNull();
});

fireEvent.click(screen.getByLabelText('resources.undefined.fields.hi'));

await waitFor(() => {
expect(
screen.getByLabelText('resources.undefined.fields.bye')
).not.toBeNull();
});
});

it('calls its children with updated scopedFormData when inside an ArrayInput', async () => {
let globalScopedFormData;
render(
<AdminContext dataProvider={testDataProvider()}>
<SimpleForm>
<ArrayInput source="authors">
<SimpleFormIterator>
<TextInput source="name" />
<FormDataConsumer>
{({
formData,
scopedFormData,
getSource,
...rest
}) => {
globalScopedFormData = scopedFormData;
return scopedFormData &&
scopedFormData.name ? (
<TextInput
source={getSource('role')}
{...rest}
/>
) : null;
}}
</FormDataConsumer>
</SimpleFormIterator>
</ArrayInput>
</SimpleForm>
</AdminContext>
);

expect(globalScopedFormData).toEqual(undefined);

fireEvent.click(screen.getByLabelText('ra.action.add'));

expect(globalScopedFormData).toEqual({ name: '' });

fireEvent.change(
screen.getByLabelText('resources.undefined.fields.authors.name'),
{
target: { value: 'a' },
}
);

await waitFor(() => {
expect(globalScopedFormData).toEqual({
name: 'a',
role: undefined,
});
});
});
});
17 changes: 11 additions & 6 deletions packages/ra-core/src/form/FormDataConsumer.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as React from 'react';
import { ReactNode } from 'react';
import { useWatch } from 'react-hook-form';
import { useWatch, useFormContext, FieldValues } from 'react-hook-form';
import get from 'lodash/get';

import warning from '../util/warning';
Expand Down Expand Up @@ -43,22 +43,27 @@ import warning from '../util/warning';
* );
*/
const FormDataConsumer = (props: ConnectedProps) => {
const formData = useWatch();
const { getValues } = useFormContext();
let formData = useWatch();
Copy link
Contributor Author

@WiXSL WiXSL Nov 8, 2022

Choose a reason for hiding this comment

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

useWatch docs:
The initial return value from useWatch will always return what's inside of defaultValue or defaultValues from useForm.

Initial discussion:
react-hook-form/react-hook-form#3758

Is not a bug, is a feature of react-hook-form.
So, this fix seems reasonable


//useWatch will initially return the provided defaultValues of the form.
//We must get the initial formData from getValues
if (Object.keys(formData).length === 0) {
(formData as FieldValues) = getValues();
}

return <FormDataConsumerView formData={formData} {...props} />;
};

export const FormDataConsumerView = (props: Props) => {
const { children, form, formData, source, index, ...rest } = props;
let scopedFormData = formData;
let getSource;
let getSourceHasBeenCalled = false;
let ret;

// If we have an index, we are in an iterator like component (such as the SimpleFormIterator)
if (typeof index !== 'undefined' && source) {
scopedFormData = get(formData, source);
getSource = (scopedSource: string) => {
const scopedFormData = get(formData, source);
const getSource = (scopedSource: string) => {
getSourceHasBeenCalled = true;
return `${source}.${scopedSource}`;
};
Expand Down