ra-core
Version:
Core components of react-admin, a frontend Framework for building admin applications on top of REST services, using ES6, React
56 lines • 2.22 kB
JavaScript
import * as React from 'react';
import { useMemo } from 'react';
import { useFormContext } from 'react-hook-form';
import { useWrappedSource } from "../../core/useWrappedSource.js";
import { useEvent } from "../../util/index.js";
import { useArrayInput } from "./useArrayInput.js";
import { SimpleFormIteratorContext } from "./SimpleFormIteratorContext.js";
const DefaultGetItemDefaults = item => item;
export const SimpleFormIteratorBase = (props) => {
const { children, getItemDefaults: getItemDefaultsProp = DefaultGetItemDefaults, disableAutoFocus = false, } = props;
const getItemDefaults = useEvent(getItemDefaultsProp);
const finalSource = useWrappedSource('');
if (!finalSource) {
throw new Error('SimpleFormIterator can only be called within an iterator input like ArrayInput');
}
const { append, fields, move, remove } = useArrayInput(props);
const { trigger, getValues } = useFormContext();
const removeField = useEvent((index) => {
remove(index);
const isScalarArray = getValues(finalSource).every((value) => typeof value !== 'object');
if (isScalarArray) {
// Trigger validation on the Array to avoid ghost errors.
// Otherwise, validation errors on removed fields might still be displayed
trigger(finalSource);
}
});
const addField = useEvent((item = undefined) => {
append(getItemDefaults(item), { shouldFocus: !disableAutoFocus });
});
const handleReorder = useEvent((origin, destination) => {
move(origin, destination);
});
const handleArrayClear = useEvent(() => {
remove();
});
const context = useMemo(() => ({
total: fields.length,
add: addField,
clear: handleArrayClear,
remove: removeField,
reOrder: handleReorder,
source: finalSource,
}), [
addField,
fields.length,
handleArrayClear,
handleReorder,
removeField,
finalSource,
]);
if (!fields) {
return null;
}
return (React.createElement(SimpleFormIteratorContext.Provider, { value: context }, children));
};
//# sourceMappingURL=SimpleFormIteratorBase.js.map