UNPKG

ra-core

Version:

Core components of react-admin, a frontend Framework for building admin applications on top of REST services, using ES6, React

80 lines 2.88 kB
var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; import * as React from 'react'; import { useFormContext } from 'react-hook-form'; import get from 'lodash/get'; import { useFormValues } from './useFormValues'; import { useWrappedSource } from '../core'; /** * Get the current (edited) value of the record from the form and pass it * to a child function * * @example * * const PostEdit = () => ( * <Edit> * <SimpleForm<FieldValues>> * <BooleanInput source="hasEmail" /> * <FormDataConsumer> * {({ formData }) => formData.hasEmail && * <TextInput source="email" /> * } * </FormDataConsumer> * </SimpleForm> * </Edit> * ); * * @example * * const OrderEdit = () => ( * <Edit> * <SimpleForm> * <SelectInput source="country" choices={countries} /> * <FormDataConsumer<FieldValues>> * {({ formData }) => * <SelectInput * source="city" * choices={getCitiesFor(formData.country)} * /> * } * </FormDataConsumer> * </SimpleForm> * </Edit> * ); */ export var FormDataConsumer = function (props) { var form = useFormContext(); var // Don't know exactly why, but this is needed for the form values to be updated // eslint-disable-next-line @typescript-eslint/no-unused-vars isDirty = form.formState.isDirty; var formData = useFormValues(); return (React.createElement(FormDataConsumerView, __assign({ formData: formData }, props))); }; export var FormDataConsumerView = function (props) { var children = props.children, formData = props.formData, source = props.source; var result; var finalSource = useWrappedSource(source || ''); // Passes an empty string here as we don't have the children sources and we just want to know if we are in an iterator var matches = ArraySourceRegex.exec(finalSource); // If we have an index, we are in an iterator like component (such as the SimpleFormIterator) if (matches) { var scopedFormData = get(formData, matches[0]); result = children({ formData: formData, scopedFormData: scopedFormData }); } else { result = children({ formData: formData }); } return result === undefined ? null : result; }; var ArraySourceRegex = new RegExp(/.+\.\d+$/); //# sourceMappingURL=FormDataConsumer.js.map