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

[@mantine/form] use-form: Make functions referentially stable #1383

Merged
merged 3 commits into from
May 8, 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
2 changes: 1 addition & 1 deletion docs/src/docs/form/use-form.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ yarn add @mantine/form
- `schema` (optional) – [zod](https://www.npmjs.com/package/zod), [joi](https://www.npmjs.com/package/joi) or [yup](https://www.npmjs.com/package/yup) validation schema, if provided `validate` is ignored
- `initialErrors` (optional) – initial form errors, object of React nodes

Hook returns an object with the following properties:
Hook returns an object with the following properties (the functions are all referentially stable):

- `values` – current form values
- `setValues` – handler to set all form values
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { act, renderHook } from '@testing-library/react-hooks';
import { useForm } from '../index';

describe('@mantine/form/use-form stable functions', () => {
it('keeps returned functions stable', () => {
const hook = renderHook(() =>
useForm({ initialValues: { banana: 'initial banana', orange: 20, apple: { nested: true } } })
);

const originalFunctions = {
...hook.result.current,
};
delete originalFunctions.values;
delete originalFunctions.errors;

act(() =>
hook.result.current.setValues({
banana: 'modified banana',
orange: 21,
apple: { nested: false },
})
);

expect(hook.result.current).toMatchObject(originalFunctions);
});
});
230 changes: 126 additions & 104 deletions src/mantine-form/src/use-form.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { useState } from 'react';
import { useCallback } from 'react';
import { formList, isFormList, FormList } from './form-list/form-list';
import { validateValues, validateFieldValue } from './validate-values/validate-values';
import { filterErrors } from './filter-errors/filter-errors';
import { getInputOnChange } from './get-input-on-change/get-input-on-change';
import { getErrorPath } from './get-error-path/get-error-path';
import { useStateRef } from './use-state-ref/use-state-ref';
import { usePropRef } from './use-prop-ref/use-prop-ref';
import type {
FormErrors,
FormRules,
Expand Down Expand Up @@ -69,40 +71,48 @@ export function useForm<T extends { [key: string]: any }>({
validate: rules,
schema,
}: UseFormInput<T>): UseFormReturnType<T> {
const [errors, setErrors] = useState(filterErrors(initialErrors));
const [values, setValues] = useState(initialValues);
const [errors, setErrors, errorsRef] = useStateRef(filterErrors(initialErrors));
const [values, setValues, valuesRef] = useStateRef(initialValues);
const initialValuesRef = usePropRef(initialValues);
const rulesRef = usePropRef(rules);
const schemaRef = usePropRef(schema);

const clearErrors = () => setErrors({});
const setFieldError = (field: keyof T, error: React.ReactNode) =>
setErrors((current) => ({ ...current, [field]: error }));
const clearErrors = useCallback(() => setErrors({}), []);
const setFieldError = useCallback(
(field: keyof T, error: React.ReactNode) =>
setErrors((current) => ({ ...current, [field]: error })),
[]
);

const clearFieldError = (field: keyof T) =>
setErrors((current) => {
const clone: any = { ...current };
delete clone[field];
return clone;
});
const clearFieldError = useCallback(
(field: keyof T) =>
setErrors((current) => {
const clone: any = { ...current };
delete clone[field];
return clone;
}),
[]
);

const setFieldValue = <K extends keyof T, V extends T[K]>(field: K, value: V) => {
const setFieldValue = useCallback(<K extends keyof T, V extends T[K]>(field: K, value: V) => {
setValues((currentValues) => ({ ...currentValues, [field]: value }));
clearFieldError(field);
};
}, []);

const setListItem = <K extends keyof T, V extends T[K]>(
field: K,
index: number,
value: V[K][number]
) => {
const list = values[field];
if (isFormList(list) && list[index] !== undefined) {
const cloned = [...list];
cloned[index] = value;
setFieldValue(field, formList(cloned) as any);
}
};
const setListItem = useCallback(
<K extends keyof T, V extends T[K]>(field: K, index: number, value: V[K][number]) => {
const list = valuesRef.current[field];
if (isFormList(list) && list[index] !== undefined) {
const cloned = [...list];
cloned[index] = value;
setFieldValue(field, formList(cloned) as any);
}
},
[]
);

const removeListItem = <K extends keyof T>(field: K, indices: number[] | number) => {
const list = values[field];
const removeListItem = useCallback(<K extends keyof T>(field: K, indices: number[] | number) => {
const list = valuesRef.current[field];

if (isFormList(list)) {
setFieldValue(
Expand All @@ -114,107 +124,119 @@ export function useForm<T extends { [key: string]: any }>({
) as any
);
}
};
}, []);

const addListItem = <K extends keyof T, V extends T[K]>(field: K, payload: V[number]) => {
const list = values[field];
const addListItem = useCallback(
<K extends keyof T, V extends T[K]>(field: K, payload: V[number]) => {
const list = valuesRef.current[field];

if (isFormList(list)) {
setFieldValue(field, formList([...list, payload]) as any);
}
};
if (isFormList(list)) {
setFieldValue(field, formList([...list, payload]) as any);
}
},
[]
);

const reorderListItem = <K extends keyof T>(
field: K,
{ from, to }: { from: number; to: number }
) => {
const list = values[field];
const reorderListItem = useCallback(
<K extends keyof T>(field: K, { from, to }: { from: number; to: number }) => {
const list = valuesRef.current[field];

if (isFormList(list) && list[from] !== undefined && list[to] !== undefined) {
const cloned = [...list];
const item = list[from];
if (isFormList(list) && list[from] !== undefined && list[to] !== undefined) {
const cloned = [...list];
const item = list[from];

cloned.splice(from, 1);
cloned.splice(to, 0, item);
setFieldValue(field, formList(cloned) as any);
}
};
cloned.splice(from, 1);
cloned.splice(to, 0, item);
setFieldValue(field, formList(cloned) as any);
}
},
[]
);

const validate = () => {
const results = validateValues(schema || rules, values);
const validate = useCallback(() => {
const results = validateValues(schemaRef.current || rulesRef.current, valuesRef.current);
setErrors(results.errors);
return results;
};
}, []);

const validateField = (field: string) => {
const results = validateFieldValue(field, schema || rules, values);
const validateField = useCallback((field: string) => {
const results = validateFieldValue(
field,
schemaRef.current || rulesRef.current,
valuesRef.current
);
results.hasError ? setFieldError(field, results.error) : clearFieldError(field);
return results;
};
}, []);

const onSubmit =
const onSubmit = useCallback(
(handleSubmit: (values: T, event: React.FormEvent) => void) => (event: React.FormEvent) => {
event.preventDefault();
const results = validate();
!results.hasErrors && handleSubmit(values, event);
};
!results.hasErrors && handleSubmit(valuesRef.current, event);
},
[]
);

const reset = () => {
setValues(initialValues);
const reset = useCallback(() => {
setValues(initialValuesRef.current);
clearErrors();
};
}, []);

const getInputProps = <
K extends keyof T,
U extends T[K],
L extends GetInputPropsFieldType = 'input'
>(
field: K,
{ type, withError = true }: { type?: L; withError?: boolean } = {}
): GetInputProps<L> => {
const value = values[field];
const onChange = getInputOnChange<U>((val: U) => setFieldValue(field, val)) as any;
const getInputProps = useCallback(
<K extends keyof T, U extends T[K], L extends GetInputPropsFieldType = 'input'>(
field: K,
{ type, withError = true }: { type?: L; withError?: boolean } = {}
): GetInputProps<L> => {
const value = valuesRef.current[field];
const onChange = getInputOnChange<U>((val: U) => setFieldValue(field, val)) as any;

const payload: any = type === 'checkbox' ? { checked: value, onChange } : { value, onChange };
const payload: any = type === 'checkbox' ? { checked: value, onChange } : { value, onChange };

if (withError && errors[field as any]) {
payload.error = errors[field as any];
}
if (withError && errorsRef.current[field as any]) {
payload.error = errorsRef.current[field as any];
}

return payload as any;
};
return payload as any;
},
[]
);

const getListInputProps = <
K extends keyof T,
U extends T[K][number],
LK extends keyof U,
L extends GetInputPropsFieldType = 'input'
>(
field: K,
index: number,
listField: LK,
{ type, withError = true }: { type?: L; withError?: boolean } = {}
): GetInputProps<L> => {
const list = values[field];

if (isFormList(list) && list[index] && listField in list[index]) {
const listValue = list[index];
const value = listValue[listField];
const onChange = getInputOnChange<U[LK]>((val: U[LK]) =>
setListItem(field, index, { ...listValue, [listField]: val })
) as any;
const payload: any = type === 'checkbox' ? { checked: value, onChange } : { value, onChange };
const error = errors[getErrorPath([field, index, listField])];
const getListInputProps = useCallback(
<
K extends keyof T,
U extends T[K][number],
LK extends keyof U,
L extends GetInputPropsFieldType = 'input'
>(
field: K,
index: number,
listField: LK,
{ type, withError = true }: { type?: L; withError?: boolean } = {}
): GetInputProps<L> => {
const list = valuesRef.current[field];

if (withError && error) {
payload.error = error;
}
if (isFormList(list) && list[index] && listField in list[index]) {
const listValue = list[index];
const value = listValue[listField];
const onChange = getInputOnChange<U[LK]>((val: U[LK]) =>
setListItem(field, index, { ...listValue, [listField]: val })
) as any;
const payload: any =
type === 'checkbox' ? { checked: value, onChange } : { value, onChange };
const error = errorsRef.current[getErrorPath([field, index, listField])];

return payload;
}
if (withError && error) {
payload.error = error;
}

return {} as any;
};
return payload;
}

return {} as any;
},
[]
);

return {
values,
Expand Down
11 changes: 11 additions & 0 deletions src/mantine-form/src/use-prop-ref/use-prop-ref.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import React, { useRef, useEffect } from 'react';

export function usePropRef<T>(value: T): React.MutableRefObject<T> {
const ref = useRef(value);

useEffect(() => {
ref.current = value;
}, [value]);

return ref;
}
14 changes: 14 additions & 0 deletions src/mantine-form/src/use-state-ref/use-state-ref.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import React, { useRef, useState, useEffect } from 'react';

export function useStateRef<T>(
value: T
): [T, React.Dispatch<React.SetStateAction<T>>, React.MutableRefObject<T>] {
const [state, setState] = useState(value);
const ref = useRef(state);

useEffect(() => {
ref.current = state;
}, [state]);

return [state, setState, ref];
}