synapse-react-client
Version:
[](https://travis-ci.com/Sage-Bionetworks/Synapse-React-Client) [](https://badge.fury.io/js/synaps
73 lines • 2.81 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.useListState = void 0;
var tslib_1 = require("tslib");
var react_1 = require("react");
/**
* This is used when a component's state uses a List<T> and has child components
* that are responsible for creating, updating, deleting the objects within the List.
*
*
* This should be used in conjunction with list.map() to generate child elements.
*
* The handle*() functions will generate a callback function for
* the child to use to perform an item change, or removal on the list.
*
* Generally, appending items to the list will be handled by the parent
* so appendToList() is just a regular function instead of a function generator
* For Example:
*
* ```
* export const ParentComponent: React.FunctionComponent<ParentComponentProps> = ({
* prop1,
* prop2,
* }) => {
* const {list: myList,
* handleListChange: handleMyListChange,
* handleListRemove: handleMyListPush,
* appendToList: handleMyListRemove} = useListState<string>(['asdf','qwerty'])
*
* return (
* <div>
* myList.map((item, index) => {
return <ChildComponent
value={item}
onChange={handleMyListChange(index)}
onRemove={handleMyListRemove(index)}
/>
})
<button onClick={(event) => {appendToList("some new value")} }> >Add Child</button>
* </div>
* )
*
* }
* ```
*
*
* @param initialState The initial value of the array
* @returns an ListStateReturn object containing the useState value and additonal change/remove/push hnndlers. Use object destructuring
*/
var useListState = function (initialState) {
var _a = (0, react_1.useState)(initialState), list = _a[0], setList = _a[1];
var handleListChange = function (index) { return function (changedValue) {
var modifiedList = (0, tslib_1.__spreadArray)([], list, true);
modifiedList[index] = changedValue;
setList(modifiedList);
}; };
var handleListRemove = function (index) { return function () {
var modifiedList = list.filter(function (value, arr_index) { return index !== arr_index; });
setList(modifiedList);
}; };
var appendToList = function () {
var newItem = [];
for (var _i = 0; _i < arguments.length; _i++) {
newItem[_i] = arguments[_i];
}
var modifiedList = (0, tslib_1.__spreadArray)([], list, true);
modifiedList.push.apply(modifiedList, newItem);
setList(modifiedList);
};
return { list: list, handleListChange: handleListChange, handleListRemove: handleListRemove, appendToList: appendToList, setList: setList };
};
exports.useListState = useListState;
//# sourceMappingURL=useListState.js.map