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

[Form lib] Add useFormData() hook to listen to fields value changes #76107

Merged
merged 17 commits into from
Sep 1, 2020
Merged
Show file tree
Hide file tree
Changes from 13 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
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import React, { ReactNode } from 'react';
import { EuiForm } from '@elastic/eui';

import { FormProvider } from '../form_context';
import { FormDataContextProvider } from '../form_data_context';
import { FormHook } from '../types';

interface Props {
Expand All @@ -30,8 +31,14 @@ interface Props {
[key: string]: any;
}

export const Form = ({ form, FormWrapper = EuiForm, ...rest }: Props) => (
<FormProvider form={form}>
<FormWrapper {...rest} />
</FormProvider>
);
export const Form = ({ form, FormWrapper = EuiForm, ...rest }: Props) => {
const { getFormData, __getFormData$ } = form;

return (
<FormDataContextProvider getFormData={getFormData} getFormData$={__getFormData$}>
<FormProvider form={form}>
<FormWrapper {...rest} />
</FormProvider>
</FormDataContextProvider>
);
};
Original file line number Diff line number Diff line change
Expand Up @@ -75,16 +75,7 @@ describe('<FormDataProvider />', () => {
setInputValue('lastNameField', 'updated value');
});

/**
* The children will be rendered three times:
* - Twice for each input value that has changed
* - once because after updating both fields, the **form** isValid state changes (from "undefined" to "true")
* causing a new "form" object to be returned and thus a re-render.
*
* When the form object will be memoized (in a future PR), te bellow call count should only be 2 as listening
* to form data changes should not receive updates when the "isValid" state of the form changes.
*/
expect(onFormData.mock.calls.length).toBe(3);
expect(onFormData).toBeCalledTimes(2);

const [formDataUpdated] = onFormData.mock.calls[onFormData.mock.calls.length - 1] as Parameters<
OnUpdateHandler
Expand Down Expand Up @@ -130,7 +121,7 @@ describe('<FormDataProvider />', () => {
find,
} = setup() as TestBed;

expect(onFormData.mock.calls.length).toBe(0); // Not present in the DOM yet
expect(onFormData).toBeCalledTimes(0); // Not present in the DOM yet

// Make some changes to the form fields
await act(async () => {
Expand Down Expand Up @@ -188,7 +179,7 @@ describe('<FormDataProvider />', () => {
setInputValue('lastNameField', 'updated value');
});

expect(onFormData.mock.calls.length).toBe(0);
expect(onFormData).toBeCalledTimes(0);
});

test('props.pathsToWatch (Array<string>): should not re-render the children when the field that changed is not in the watch list', async () => {
Expand Down Expand Up @@ -228,14 +219,14 @@ describe('<FormDataProvider />', () => {
});

// No re-render
expect(onFormData.mock.calls.length).toBe(0);
expect(onFormData).toBeCalledTimes(0);

// Make some changes to fields in the watch list
await act(async () => {
setInputValue('nameField', 'updated value');
});

expect(onFormData.mock.calls.length).toBe(1);
expect(onFormData).toBeCalledTimes(1);

onFormData.mockReset();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,57 +17,20 @@
* under the License.
*/

import React, { useState, useEffect, useRef, useCallback } from 'react';
import React from 'react';

import { FormData } from '../types';
import { useFormContext } from '../form_context';
import { useFormData } from '../hooks';

interface Props {
children: (formData: FormData) => JSX.Element | null;
pathsToWatch?: string | string[];
}

export const FormDataProvider = React.memo(({ children, pathsToWatch }: Props) => {
const form = useFormContext();
const { subscribe } = form;
const previousRawData = useRef<FormData>(form.__getFormData$().value);
const isMounted = useRef(false);
const [formData, setFormData] = useState<FormData>(previousRawData.current);
const { 0: formData, 2: isReady } = useFormData({ watch: pathsToWatch });

const onFormData = useCallback(
({ data: { raw } }) => {
// To avoid re-rendering the children for updates on the form data
// that we are **not** interested in, we can specify one or multiple path(s)
// to watch.
if (pathsToWatch) {
const valuesToWatchArray = Array.isArray(pathsToWatch)
? (pathsToWatch as string[])
: ([pathsToWatch] as string[]);

if (valuesToWatchArray.some((value) => previousRawData.current[value] !== raw[value])) {
previousRawData.current = raw;
setFormData(raw);
}
} else {
setFormData(raw);
}
},
[pathsToWatch]
);

useEffect(() => {
const subscription = subscribe(onFormData);
return subscription.unsubscribe;
}, [subscribe, onFormData]);

useEffect(() => {
isMounted.current = true;
return () => {
isMounted.current = false;
};
}, []);

if (!isMounted.current && Object.keys(formData).length === 0) {
if (!isReady) {
// No field has mounted yet, don't render anything
return null;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

import React, { createContext, useContext, useMemo } from 'react';

import { FormData, FormHook } from './types';
import { Subject } from './lib';

export interface Context<T extends FormData = FormData> {
getFormData$: () => Subject<FormData>;
getFormData: FormHook<T>['getFormData'];
}

const FormDataContext = createContext<Context<any> | undefined>(undefined);

interface Props extends Context {
children: React.ReactNode;
}

export const FormDataContextProvider = ({ children, getFormData$, getFormData }: Props) => {
const value = useMemo<Context>(
() => ({
getFormData,
getFormData$,
}),
[getFormData, getFormData$]
);

return <FormDataContext.Provider value={value}>{children}</FormDataContext.Provider>;
};

export function useFormDataContext<T extends FormData = FormData>() {
return useContext<Context<T> | undefined>(FormDataContext);
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,4 @@

export { useField } from './use_field';
export { useForm } from './use_form';
export { useFormData } from './use_form_data';
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ const onFormHook = (_form: FormHook<any>) => {
formHook = _form;
};

describe('use_form() hook', () => {
describe('useForm() hook', () => {
beforeEach(() => {
formHook = null;
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,12 @@ export function useForm<T extends FormData = FormData>(

if (!field.isValidated) {
setIsValid(undefined);

// When we submit the form (and set "isSubmitted" to "true"), we validate **all fields**.
// If a field is added and it is not validated it means that we have swapped fields and added new ones:
// --> we have basically have a new form in front of us.
// For that reason we make sure that the "isSubmitted" state is false.
setIsSubmitted(false);
}
},
[updateFormDataAt]
Expand Down Expand Up @@ -389,6 +395,7 @@ export function useForm<T extends FormData = FormData>(
isValid,
id,
submit: submitForm,
validate: validateAllFields,
subscribe,
setFieldValue,
setFieldErrors,
Expand Down Expand Up @@ -428,6 +435,7 @@ export function useForm<T extends FormData = FormData>(
addField,
removeField,
validateFields,
validateAllFields,
]);

useEffect(() => {
Expand Down
Loading