import { Field } from 'react-final-form';
import React from 'react';
import { required } from 'store/utils/validation';

const identity = value => value;

/* This wraps react-final-form's <Field/> component.
 * The identity function ensures form values never get set to null,
 * but rather, empty strings.
 * This should only be used on non required fields
 *
 * See https://github.com/final-form/react-final-form/issues/130
 */
const FieldAdapter = props => {
  const { isRequired } = props;

  const otherProps = {
    validate: isRequired ? required : null,
  };
  if (!isRequired) {
    otherProps.parse = identity;
  }

  return <Field {...otherProps} {...props} />;
};

export default FieldAdapter;
