Skip to content

Commit dddaa43

Browse files
committed
Add useEditItemField and useItemApi hooks
1 parent 4c93b20 commit dddaa43

File tree

1 file changed

+53
-1
lines changed

1 file changed

+53
-1
lines changed

packages/react/src/index.tsx

Lines changed: 53 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,13 @@ import {
55
useEffect,
66
ReactNode,
77
} from 'react';
8-
import { type Store, type Event, type Effect, clearNode } from 'effector';
8+
import {
9+
type Store,
10+
type Event,
11+
type Effect,
12+
type EventCallable,
13+
clearNode,
14+
} from 'effector';
915
import { useList, useStoreMap, useUnit } from 'effector-react';
1016

1117
import type {
@@ -249,3 +255,49 @@ export function useReadItem<T>(
249255
if (idx === -1) return keyval.defaultState;
250256
return result as T;
251257
}
258+
259+
export function useItemApi<T, Api>(
260+
keyval: Keyval<any, T, Api, any>,
261+
key: string | number,
262+
): {
263+
[K in keyof Api]: Api[K] extends EventCallable<infer V>
264+
? (params: V) => void
265+
: never;
266+
} {
267+
const commonApi = useUnit(keyval.api);
268+
return useMemo(() => {
269+
const result = {} as any;
270+
for (const field in commonApi) {
271+
const fn = (data: any) =>
272+
//@ts-expect-error
273+
commonApi[field]({
274+
key,
275+
data,
276+
});
277+
result[field] = fn;
278+
}
279+
return result;
280+
}, [keyval, key, commonApi]);
281+
}
282+
283+
export function useEditItemField<Input>(
284+
keyval: Keyval<Input, any, any, any>,
285+
key: string | number,
286+
): {
287+
[K in keyof Input]: (params: Input[K]) => void;
288+
} {
289+
const commonApi = useUnit(keyval.editField);
290+
return useMemo(() => {
291+
const result = {} as any;
292+
for (const field in commonApi) {
293+
const fn = (data: any) =>
294+
//@ts-expect-error
295+
commonApi[field]({
296+
key,
297+
data,
298+
});
299+
result[field] = fn;
300+
}
301+
return result;
302+
}, [keyval, key, commonApi]);
303+
}

0 commit comments

Comments
 (0)