UNPKG

@sparklink-pro/apant

Version:

Apollo & Antd tools

50 lines 1.93 kB
import { useMemo } from 'react'; import { get, isString, isFunction, isArray, isPlainObject, set } from 'lodash-es'; const isTypeObject = (o) => isPlainObject(o) && isString(o.__typename); const resolveInitialValue = ({ field, context }) => { const { item: { name }, initialValue, } = field; if (!name) { return null; } // If we have an initial value set and it is a function, call it regardless if (isFunction(initialValue)) { return initialValue({ context, object: get(context.object, name) }); } const value = get(context.object, name, field.initialValue || null); const hasObject = context.object !== undefined; // We have an object if (hasObject) { if (field.list) { if (!isArray(value)) { return []; } if (!field.fields || field.fields.length === 0) { return value; } // eslint-disable-next-line @typescript-eslint/no-use-before-define return value.map((v) => resolveInitialValues({ fields: field.fields, context: Object.assign(Object.assign({}, context), { object: v }) })); } if (isArray(value)) { return value.map((o) => (isTypeObject(o) ? o.id : o)); } if (isTypeObject(value)) { return value.id; } return value; } return initialValue; }; const resolveInitialValues = ({ fields, context }) => { const initialValues = {}; fields.forEach((field) => { const { item: { name }, } = field; if (!name) { return; } set(initialValues, name, resolveInitialValue({ field, context })); }); return initialValues; }; export const useInitialValues = ({ fields, context }) => useMemo(() => resolveInitialValues({ fields, context }), [fields, context]); export default useInitialValues; //# sourceMappingURL=useInitialValues.js.map