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

feat(useWatch): notify watch in preserve mode #577

Merged
merged 1 commit into from
Mar 13, 2023
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
7 changes: 5 additions & 2 deletions docs/examples/useWatch.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ type FieldType = {
demo2?: string;
id?: number;
demo1?: { demo2?: { demo3?: { demo4?: string } } };
hidden?: string;
};

const Demo = React.memo(() => {
Expand Down Expand Up @@ -48,12 +49,13 @@ export default () => {
const demo4 = Form.useWatch(['demo1', 'demo2', 'demo3', 'demo4'], form);
const demo5 = Form.useWatch(['demo1', 'demo2', 'demo3', 'demo4', 'demo5'], form);
const more = Form.useWatch(['age', 'name', 'gender'], form);
console.log('main watch', values, demo1, demo2, main, age, demo3, demo4, demo5, more);
const hidden = Form.useWatch(['hidden'], { form, preserve: true });
console.log('main watch', values, demo1, demo2, main, age, demo3, demo4, demo5, more, hidden);
return (
<>
<Form
form={form}
initialValues={{ id: 1, age: '10', name: 'default' }}
initialValues={{ id: 1, age: '10', name: 'default', hidden: 'here' }}
onFinish={v => console.log('submit values', v)}
>
no render
Expand Down Expand Up @@ -115,6 +117,7 @@ export default () => {
<button onClick={() => setVisible(c => !c)}>isShow name</button>
<button onClick={() => setVisible3(c => !c)}>isShow initialValue</button>
<button onClick={() => setVisible2(c => !c)}>isShow demo2</button>
<button onClick={() => form.setFieldsValue({ hidden: `${form.getFieldsValue(true).hidden || ''}1` })}>change hidden field</button>
</>
);
};
11 changes: 10 additions & 1 deletion src/interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,16 @@ export interface Callbacks<Values = any> {
onFinishFailed?: (errorInfo: ValidateErrorEntity<Values>) => void;
}

export type WatchCallBack = (values: Store, namePathList: InternalNamePath[]) => void;
export type WatchCallBack = (
values: Store,
allValues: Store,
namePathList: InternalNamePath[],
) => void;

export interface WatchOptions<Form extends FormInstance = FormInstance> {
form?: Form;
preserve?: boolean;
}

export interface InternalHooks {
dispatch: (action: ReducerAction) => void;
Expand Down
5 changes: 3 additions & 2 deletions src/useForm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -200,9 +200,10 @@ export class FormStore {
// No need to cost perf when nothing need to watch
if (this.watchList.length) {
const values = this.getFieldsValue();
const allValues = this.getFieldsValue(true);

this.watchList.forEach(callback => {
callback(values, namePath);
callback(values, allValues, namePath);
});
}
};
Expand Down Expand Up @@ -548,7 +549,7 @@ export class FormStore {
const namePathList: InternalNamePath[] = [];

fields.forEach((fieldData: FieldData) => {
const { name, errors, ...data } = fieldData;
const { name, ...data } = fieldData;
const namePath = getNamePath(name);
namePathList.push(namePath);

Expand Down
48 changes: 35 additions & 13 deletions src/useWatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,16 @@ import type { FormInstance } from '.';
import { FieldContext } from '.';
import warning from 'rc-util/lib/warning';
import { HOOK_MARK } from './FieldContext';
import type { InternalFormInstance, InternalNamePath, NamePath, Store } from './interface';
import type {
InternalFormInstance,
InternalNamePath,
NamePath,
Store,
WatchOptions,
} from './interface';
import { useState, useContext, useEffect, useRef, useMemo } from 'react';
import { getNamePath, getValue } from './utils/valueUtil';
import { isFormInstance } from './utils/typeUtil';

type ReturnPromise<T> = T extends Promise<infer ValueType> ? ValueType : never;
type GetGeneric<TForm extends FormInstance> = ReturnPromise<ReturnType<TForm['validateFields']>>;
Expand Down Expand Up @@ -38,7 +45,7 @@ function useWatch<
TDependencies4 extends keyof GetGeneric<TForm>[TDependencies1][TDependencies2][TDependencies3],
>(
dependencies: [TDependencies1, TDependencies2, TDependencies3, TDependencies4],
form?: TForm,
form?: TForm | WatchOptions<TForm>,
): GetGeneric<TForm>[TDependencies1][TDependencies2][TDependencies3][TDependencies4];

function useWatch<
Expand All @@ -48,7 +55,7 @@ function useWatch<
TDependencies3 extends keyof GetGeneric<TForm>[TDependencies1][TDependencies2],
>(
dependencies: [TDependencies1, TDependencies2, TDependencies3],
form?: TForm,
form?: TForm | WatchOptions<TForm>,
): GetGeneric<TForm>[TDependencies1][TDependencies2][TDependencies3];

function useWatch<
Expand All @@ -57,22 +64,34 @@ function useWatch<
TDependencies2 extends keyof GetGeneric<TForm>[TDependencies1],
>(
dependencies: [TDependencies1, TDependencies2],
form?: TForm,
form?: TForm | WatchOptions<TForm>,
): GetGeneric<TForm>[TDependencies1][TDependencies2];

function useWatch<TDependencies extends keyof GetGeneric<TForm>, TForm extends FormInstance>(
dependencies: TDependencies | [TDependencies],
form?: TForm,
form?: TForm | WatchOptions<TForm>,
): GetGeneric<TForm>[TDependencies];

function useWatch<TForm extends FormInstance>(dependencies: [], form?: TForm): GetGeneric<TForm>;
function useWatch<TForm extends FormInstance>(
dependencies: [],
form?: TForm | WatchOptions<TForm>,
): GetGeneric<TForm>;

function useWatch<TForm extends FormInstance>(dependencies: NamePath, form?: TForm): any;
function useWatch<TForm extends FormInstance>(
dependencies: NamePath,
form?: TForm | WatchOptions<TForm>,
): any;

function useWatch<ValueType = Store>(dependencies: NamePath, form?: FormInstance): ValueType;
function useWatch<ValueType = Store>(
dependencies: NamePath,
form?: FormInstance | WatchOptions<FormInstance>,
): ValueType;

function useWatch(...args: [NamePath, FormInstance | WatchOptions<FormInstance>]) {
const [dependencies = [], _form = {}] = args;
const options = isFormInstance(_form) ? { form: _form } : _form;
const form = options.form;

function useWatch(...args: [NamePath, FormInstance]) {
const [dependencies = [], form] = args;
const [value, setValue] = useState<any>();

const valueStr = useMemo(() => stringify(value), [value]);
Expand Down Expand Up @@ -107,8 +126,8 @@ function useWatch(...args: [NamePath, FormInstance]) {
const { getFieldsValue, getInternalHooks } = formInstance;
const { registerWatch } = getInternalHooks(HOOK_MARK);

const cancelRegister = registerWatch(store => {
const newValue = getValue(store, namePathRef.current);
const cancelRegister = registerWatch((values, allValues) => {
const newValue = getValue(options.preserve ? allValues : values, namePathRef.current);
const nextValueStr = stringify(newValue);

// Compare stringify in case it's nest object
Expand All @@ -119,7 +138,10 @@ function useWatch(...args: [NamePath, FormInstance]) {
});

// TODO: We can improve this perf in future
const initialValue = getValue(getFieldsValue(), namePathRef.current);
const initialValue = getValue(
options.preserve ? getFieldsValue(true) : getFieldsValue(),
namePathRef.current,
);
setValue(initialValue);

return cancelRegister;
Expand Down
6 changes: 6 additions & 0 deletions src/utils/typeUtil.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
import type { FormInstance, InternalFormInstance } from '../interface';

export function toArray<T>(value?: T | T[] | null): T[] {
if (value === undefined || value === null) {
return [];
}

return Array.isArray(value) ? value : [value];
}

export function isFormInstance<T>(form: T | FormInstance): form is FormInstance {
return form && !!(form as InternalFormInstance)._init;
}
30 changes: 30 additions & 0 deletions tests/useWatch.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -407,4 +407,34 @@ describe('useWatch', () => {
);
errorSpy.mockRestore();
});

it('useWatch with preserve option', async () => {
const logSpy = jest.spyOn(console, 'log').mockImplementation(() => {});
const Demo: React.FC = () => {
const [form] = Form.useForm();
const nameValuePreserve = Form.useWatch<string>('name', {
form,
preserve: true,
});
const nameValue = Form.useWatch<string>('name', form);
React.useEffect(() => {
console.log(nameValuePreserve, nameValue);
}, [nameValuePreserve, nameValue]);
return (
<div>
<Form form={form} initialValues={{ name: 'bamboo' }} />
<div className="values">{nameValuePreserve}</div>
<button className="test-btn" onClick={() => form.setFieldValue('name', 'light')} />
</div>
);
};
await act(async () => {
const { container } = render(<Demo />);
await timeout();
expect(logSpy).toHaveBeenCalledWith('bamboo', undefined); // initialValue
fireEvent.click(container.querySelector('.test-btn'));
await timeout();
expect(logSpy).toHaveBeenCalledWith('light', undefined); // after setFieldValue
});
});
});