Skip to content

Commit

Permalink
Merge pull request #22 from jungsoft/21-values-should-be-touched-when…
Browse files Browse the repository at this point in the history
…-initialized

21 values should be touched when initialized
  • Loading branch information
pedro-lb authored Jul 1, 2020
2 parents d620adf + 0eba666 commit fa0243a
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
8 changes: 8 additions & 0 deletions packages/core/src/hooks/useFormup.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
import FormInputGroupItem from '../components/FormInputGroupItem/FormInputGroupItem';
import mapInitialValuesFromSchema from '../utils/mapInitialValuesFromSchema';
import FormInputGroup from '../components/FormInputGroup/FormInputGroup';
import mapInitialTouched from '../utils/mapInitialTouched';
import FormInput from '../components/FormInput/FormInput';
import validateForm from '../yup/validateForm';
import useHasMounted from './useHasMounted';
Expand Down Expand Up @@ -40,11 +41,18 @@ const useFormup = (
schema,
]);

const initialTouched = React.useMemo(() => (
mapInitialTouched(options?.initialValues, options?.initialTouched)
), [
options,
]);

const useFormikResult = useFormik({
...options,
validateOnMount: !hasMounted && options.validateOnMount,
onSubmit: options?.onSubmit || noop,
validationSchema: schema,
initialTouched,
initialValues,
});

Expand Down
52 changes: 52 additions & 0 deletions packages/core/src/utils/mapInitialTouched.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/**
* Recursively maps touched fields in an object.
* @param obj The object
*/
const recursiveMapTouched = (obj: object): object => {
const result = {
...(obj || {}),
};

Object
.keys(result)
.forEach((key) => {
const value = result[key];

if (typeof value === 'object') {
recursiveMapTouched(value);
return;
}

// eslint-disable-next-line no-param-reassign
result[key] = true;
});

return result;
};

/**
* Recursively maps initial touched fields according to custom initial values.
* Any value initialized with initialValues will be marked as touched.
*
* You can override the touched values by passing an object as the second parameter,
* which is optional.
*
* @param initialValues Value of initialValues
* @param initialTouched Value of initialTouched
*/
const mapInitialTouched = (
initialValues?: object,
initialTouched?: object,
) => {
if (initialTouched) {
return initialTouched;
}

if (!initialValues) {
return undefined;
}

return recursiveMapTouched(initialValues);
};

export default mapInitialTouched;

0 comments on commit fa0243a

Please sign in to comment.