Skip to content

Commit c033d9b

Browse files
author
nicosammito
committed
refactor: improve constructor handling in useReactiveArrayService
1 parent b9efeb6 commit c033d9b

1 file changed

Lines changed: 23 additions & 11 deletions

File tree

src/utils/reactiveArrayService.ts

Lines changed: 23 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -70,32 +70,44 @@ export function useReactiveArrayService<K, S extends ArrayService<K>>(
7070
Ctor: ArrayServiceCtor<K, S> | ((store: ReactiveArrayStore<K>) => S),
7171
initial: InitialArg<K, S> = []
7272
): [K[], S] {
73-
7473
const [state, setState] = React.useState<K[]>(
7574
Array.isArray(initial) ? initial : []
7675
);
76+
7777
const ref = React.useRef(state);
7878
React.useEffect(() => {
7979
ref.current = state;
8080
}, [state]);
8181

8282
const getState = React.useCallback(() => ref.current, []);
8383

84-
const service = React.useMemo(() =>
85-
(
86-
typeof Ctor === "function"
87-
&& Ctor.prototype
88-
&& Object.getOwnPropertyNames(Ctor.prototype).some((n) => n !== "constructor"
89-
)
90-
) ? (
91-
(Ctor as ((store: ReactiveArrayStore<K>) => S))({getState, setState})
92-
) : new (Ctor as ArrayServiceCtor<K, S>)({getState, setState}), [Ctor, getState, setState]);
84+
const service = React.useMemo(() => {
85+
const store = {getState, setState};
86+
87+
const handler = {
88+
construct() {
89+
return handler
90+
}
91+
}
92+
93+
const isConstructor = (x: any) => {
94+
try {
95+
return !!(new (new Proxy(x, handler))())
96+
} catch (e) {
97+
return false
98+
}
99+
}
100+
101+
return isConstructor(Ctor)
102+
? new (Ctor as ArrayServiceCtor<K, S>)(store) // Klasse → mit new
103+
: (Ctor as (store: ReactiveArrayStore<K>) => S)(store); // Factory → direkt aufrufen
104+
}, [Ctor, getState, setState]);
93105

94106
React.useEffect(() => {
95107
if (typeof initial === "function") {
96108
setState((initial as (svc: S) => K[])(service));
97109
}
98-
}, [service]);
110+
}, [service, initial]);
99111

100112
return [state, service];
101113
}

0 commit comments

Comments
 (0)