Skip to content

Commit b8b8373

Browse files
committed
Use union for AsyncState type
1 parent f856918 commit b8b8373

File tree

1 file changed

+25
-19
lines changed

1 file changed

+25
-19
lines changed

src/index.ts

Lines changed: 25 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -43,12 +43,31 @@ export type AsyncStateStatus =
4343
| 'success'
4444
| 'error';
4545

46-
export type AsyncState<R> = {
47-
status: AsyncStateStatus;
48-
loading: boolean;
49-
error: Error | undefined;
50-
result: R | undefined;
51-
};
46+
export declare type AsyncState<R> =
47+
| {
48+
status: 'not-requested';
49+
loading: false;
50+
result: undefined;
51+
error: undefined;
52+
}
53+
| {
54+
status: 'loading';
55+
loading: true;
56+
error: undefined;
57+
result: undefined;
58+
}
59+
| {
60+
status: 'success';
61+
loading: false;
62+
error: undefined;
63+
result: R;
64+
}
65+
| {
66+
status: 'error';
67+
loading: false;
68+
error: Error;
69+
result: undefined;
70+
};
5271
type SetLoading<R> = (asyncState: AsyncState<R>) => AsyncState<R>;
5372
type SetResult<R> = (result: R, asyncState: AsyncState<R>) => AsyncState<R>;
5473
type SetError<R> = (error: Error, asyncState: AsyncState<R>) => AsyncState<R>;
@@ -135,7 +154,6 @@ const normalizeOptions = <R>(
135154
type UseAsyncStateResult<R> = {
136155
value: AsyncState<R>;
137156
set: Dispatch<SetStateAction<AsyncState<R>>>;
138-
merge: (value: Partial<AsyncState<R>>) => void;
139157
reset: () => void;
140158
setLoading: () => void;
141159
setResult: (r: R) => void;
@@ -167,19 +185,9 @@ const useAsyncState = <R extends {}>(
167185
[value, setValue]
168186
);
169187

170-
const merge = useCallback(
171-
(state: Partial<AsyncState<R>>) =>
172-
setValue({
173-
...value,
174-
...state,
175-
}),
176-
[value, setValue]
177-
);
178-
179188
return {
180189
value,
181190
set: setValue,
182-
merge,
183191
reset,
184192
setLoading,
185193
setResult,
@@ -217,7 +225,6 @@ export type UseAsyncReturn<
217225
Args extends any[] = UnknownArgs
218226
> = AsyncState<R> & {
219227
set: (value: AsyncState<R>) => void;
220-
merge: (value: Partial<AsyncState<R>>) => void;
221228
reset: () => void;
222229
execute: (...args: Args) => Promise<R>;
223230
currentPromise: Promise<R> | null;
@@ -298,7 +305,6 @@ const useAsyncInternal = <R = UnknownResult, Args extends any[] = UnknownArgs>(
298305
return {
299306
...AsyncState.value,
300307
set: AsyncState.set,
301-
merge: AsyncState.merge,
302308
reset: AsyncState.reset,
303309
execute: executeAsyncOperationMemo,
304310
currentPromise: CurrentPromise.get(),

0 commit comments

Comments
 (0)