@shopify/react-form
Version:
Manage React forms tersely and safely-typed with no magic using React hooks
63 lines (56 loc) • 2 kB
JavaScript
;
Object.defineProperty(exports, '__esModule', { value: true });
var baselist = require('./baselist.js');
var reducer = require('./hooks/reducer.js');
/*
A custom hook for dynamically adding and removing field items. This utilizes the base functionality of useBaseList.
* @param listOrConfig - A configuration object specifying both the value and validation config.
* @param fieldFactory - A factory function that produces field items according to the list items originally passed in for listOrConfig.
* @param validationDependencies - An array of dependencies to use to decide when to regenerate validators.
* @returns A list of dictionaries of `Field` objects representing the state of your input, an addItem function for adding list items (this calls your factory), and a removeItem function for removing list items by index.
*/
function useDynamicList(listOrConfig, fieldFactory, validationDependencies = []) {
const {
fields,
dispatch,
reset,
dirty,
newDefaultValue,
value,
defaultValue
} = baselist.useBaseList(listOrConfig, validationDependencies);
function addItem(factoryArgument) {
const itemToAdd = fieldFactory(factoryArgument);
if (Array.isArray(itemToAdd)) {
dispatch(reducer.addFieldItemAction(itemToAdd));
} else {
dispatch(reducer.addFieldItemAction([itemToAdd]));
}
}
function editItem(editedItem, index) {
dispatch(reducer.editFieldItemAction(editedItem, index));
}
function moveItem(fromIndex, toIndex) {
dispatch(reducer.moveFieldItemAction(fromIndex, toIndex));
}
function removeItem(index) {
dispatch(reducer.removeFieldItemAction(index));
}
function removeItems(indicesToRemove) {
dispatch(reducer.removeFieldItemsAction(indicesToRemove));
}
return {
fields,
addItem,
editItem,
removeItem,
removeItems,
moveItem,
reset,
dirty,
value,
newDefaultValue,
defaultValue
};
}
exports.useDynamicList = useDynamicList;