ra-core
Version:
Core components of react-admin, a frontend Framework for building admin applications on top of REST services, using ES6, React
69 lines • 2.44 kB
JavaScript
import * as React from 'react';
import { useFormContext } from 'react-hook-form';
import get from 'lodash/get.js';
import { useFormValues } from "./useFormValues.js";
import { useWrappedSource } from "../core/index.js";
/**
* 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 const FormDataConsumer = (props) => {
const form = useFormContext();
const { formState: {
// 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;
const formData = useFormValues();
return (React.createElement(FormDataConsumerView, { formData: formData, ...props }));
};
export const FormDataConsumerView = (props) => {
const { children, formData, source } = props;
let result;
const 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
const matches = ArraySourceRegex.exec(finalSource);
// If we have an index, we are in an iterator like component (such as the SimpleFormIterator)
if (matches) {
const scopedFormData = get(formData, matches[0]);
result = children({ formData, scopedFormData });
}
else {
result = children({ formData });
}
return result === undefined ? null : result;
};
const ArraySourceRegex = new RegExp(/.+\.\d+$/);
//# sourceMappingURL=FormDataConsumer.js.map