feat(react): Support Mutiple useOnSelectionChange Hook subscribers

This commit is contained in:
spky
2023-11-03 00:48:46 +01:00
parent 428fced240
commit bbd5973d66
6 changed files with 69 additions and 686 deletions
@@ -4,14 +4,19 @@ import { useStoreApi } from './useStore';
import type { OnSelectionChangeFunc } from '../types';
export type UseOnSelectionChangeOptions = {
onChange?: OnSelectionChangeFunc;
onChange: OnSelectionChangeFunc;
};
function useOnSelectionChange({ onChange }: UseOnSelectionChangeOptions) {
const store = useStoreApi();
useEffect(() => {
store.setState({ onSelectionChange: onChange });
const addedOnSelectionChange = [...store.getState().onSelectionChange, onChange];
store.setState({ onSelectionChange: addedOnSelectionChange });
return () => {
const removedOnSelectionChange = store.getState().onSelectionChange.filter((fn) => fn !== onChange);
store.setState({ onSelectionChange: removedOnSelectionChange });
};
}, [onChange]);
}