feat(hooks): add useNodesState and useEdgesState

This commit is contained in:
moklick
2021-11-26 14:39:22 +01:00
parent 713e7e1bd4
commit a032306408
8 changed files with 66 additions and 76 deletions
+27
View File
@@ -0,0 +1,27 @@
import { useState, useCallback, SetStateAction, Dispatch } from 'react';
import { applyNodeChanges, applyEdgeChanges } from '../utils/changes';
import { Node, NodeChange, Edge, EdgeChange } from '../types';
type ApplyChanges<ItemType, ChangesType> = (changes: ChangesType[], items: ItemType[]) => ItemType[];
type OnChange<ChangesType> = (changes: ChangesType[]) => void;
// returns a hook that can be used liked this:
// const [nodes, setNodes, onNodesChange] = useNodesState(intialNodes);
function createUseItemsState<ItemType, ChangesType>(
applyChangesFunction: ApplyChanges<ItemType, ChangesType>
): (initialItems: ItemType[]) => [ItemType[], Dispatch<SetStateAction<ItemType[]>>, OnChange<ChangesType>] {
return (initialItems: ItemType[]) => {
const [items, setItems] = useState<ItemType[]>(initialItems);
const onItemsChange = useCallback(
(changes: ChangesType[]) => setItems((items) => applyChangesFunction(changes, items)),
[]
);
return [items, setItems, onItemsChange];
};
}
export const useNodesState = createUseItemsState<Node, NodeChange>(applyNodeChanges as ApplyChanges<Node, NodeChange>);
export const useEdgesState = createUseItemsState<Edge, EdgeChange>(applyEdgeChanges as ApplyChanges<Edge, EdgeChange>);
+1
View File
@@ -27,6 +27,7 @@ export { applyNodeChanges, applyEdgeChanges } from './utils/changes';
export { default as useZoomPanHelper } from './hooks/useZoomPanHelper';
export { default as useUpdateNodeInternals } from './hooks/useUpdateNodeInternals';
export * from './hooks/useNodesEdgesState';
export * from './additional-components';
export { useStore, useStoreApi } from './store';