import * as React from 'react'; import { ReactNode } from 'react'; import { useWatch } from 'react-hook-form'; import get from 'lodash/get'; import warning from '../util/warning'; /** * Get the current (edited) value of the record from the form and pass it * to a child function * * @example * * const PostEdit = (props) => ( * * * * * {({ formData, ...rest }) => formData.hasEmail && * * } * * * * ); * * @example * * const OrderEdit = (props) => ( * * * * * {({ formData, ...rest }) => * * } * * * * ); */ const FormDataConsumer = (props: ConnectedProps) => { const formData = useWatch(); return ; }; export const FormDataConsumerView = (props: Props) => { const { children, form, formData, source, index, ...rest } = props; let scopedFormData = formData; let getSource; let getSourceHasBeenCalled = false; let ret; // If we have an index, we are in an iterator like component (such as the SimpleFormIterator) if (typeof index !== 'undefined' && source) { scopedFormData = get(formData, source); getSource = (scopedSource: string) => { getSourceHasBeenCalled = true; return `${source}.${scopedSource}`; }; ret = children({ formData, scopedFormData, getSource, ...rest }); } else { ret = children({ formData, ...rest }); } warning( typeof index !== 'undefined' && ret && !getSourceHasBeenCalled, `You're using a FormDataConsumer inside an ArrayInput and you did not call the getSource function supplied by the FormDataConsumer component. This is required for your inputs to get the proper source. {({ formData, // The whole form data scopedFormData, // The data for this item of the ArrayInput getSource, // A function to get the valid source inside an ArrayInput ...rest, }) => scopedFormData.name ? ( ) : null } ` ); return ret === undefined ? null : ret; }; export default FormDataConsumer; export interface FormDataConsumerRenderParams { formData: any; scopedFormData?: any; getSource?: (source: string) => string; } export type FormDataConsumerRender = ( params: FormDataConsumerRenderParams ) => ReactNode; interface ConnectedProps { children: FormDataConsumerRender; form?: string; record?: any; source?: string; [key: string]: any; } interface Props extends ConnectedProps { formData: any; index?: number; }