react-native-formik icon indicating copy to clipboard operation
react-native-formik copied to clipboard

[withError] Don't override formik error when error props is defined.

Open taboulot opened this issue 5 years ago • 0 comments

Problem

I need to manage errors on a field :

  • One with Yup (validationSchema);
  • One with a call to an API;

withError automatically define the prop error from Yup for my children component.

However, if then in my form I define the props error like error={hasAPIError()} I don't have Yup's errors handle automatically. I need now to create a function that handle it for me like error={hasAPIError() || hasYupError()}.

In our case we totally forget to do it because we thought that Yup's errors will always be handle and transfer to my children component.

Solution

Current withError :

import { compose, mapProps } from "recompose";
import _ from "lodash";

import withFormik from "./withFormik";

const withError = compose(
  withFormik,
  mapProps(({ formik: { errors }, name, ...props }) => ({
    error: _.get(errors, name),
    ...props,
    name
  }))
);

export default withError;

Change I propose :

import { compose, mapProps } from "recompose";
import _ from "lodash";

import withFormik from "./withFormik";

const withError = compose(
  withFormik,
  mapProps(({ formik: { errors }, name, error, ...props }) => ({
    error: _.get(errors, name) || error, // Don't override errors that Formik handle for us
    ...props,
    name
  }))
);

export default withError;

What do you think about this update ?

taboulot avatar Jun 20 '19 12:06 taboulot