Skip to content

Commit

Permalink
Remodel FieldArray validation side effect to cDU (jaredpalmer#2115)
Browse files Browse the repository at this point in the history
  • Loading branch information
jaredpalmer authored Dec 12, 2019
1 parent 53d1c47 commit b2fecda
Showing 1 changed file with 22 additions and 13 deletions.
35 changes: 22 additions & 13 deletions packages/formik/src/FieldArray.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
FormikProps,
} from './types';
import { getIn, isEmptyChildren, isFunction, setIn } from './utils';
import isEqual from 'react-fast-compare';

export type FieldArrayRenderProps = ArrayHelpers & {
form: FormikProps<any>;
Expand Down Expand Up @@ -127,34 +128,42 @@ class FieldArrayInner<Values = {}> extends React.Component<
this.pop = this.pop.bind(this) as any;
}

componentDidUpdate(
prevProps: FieldArrayConfig & { formik: FormikContextType<Values> }
) {
if (
!isEqual(
getIn(prevProps.formik.values, prevProps.name),
getIn(this.props.formik.values, this.props.name)
) &&
this.props.formik.validateOnChange
) {
this.props.formik.validateForm();
}
}

updateArrayField = (
fn: Function,
alterTouched: boolean | Function,
alterErrors: boolean | Function
) => {
const {
name,
validateOnChange,
formik: { setFormikState, validateForm },

formik: { setFormikState },
} = this.props;
setFormikState((prevState: FormikState<any>) => {
let updateErrors = typeof alterErrors === 'function' ? alterErrors : fn;
let updateTouched =
typeof alterTouched === 'function' ? alterTouched : fn;

const values = setIn(
prevState.values,
name,
fn(getIn(prevState.values, name))
);

if (validateOnChange) {
validateForm(values);
}

return {
...prevState,
values,
values: setIn(
prevState.values,
name,
fn(getIn(prevState.values, name))
),
errors: alterErrors
? setIn(
prevState.errors,
Expand Down

0 comments on commit b2fecda

Please sign in to comment.