Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 25 additions & 19 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,12 +43,31 @@ export type AsyncStateStatus =
| 'success'
| 'error';

export type AsyncState<R> = {
status: AsyncStateStatus;
loading: boolean;
error: Error | undefined;
result: R | undefined;
};
export declare type AsyncState<R> =
| {
status: 'not-requested';
loading: false;
result: undefined;
error: undefined;
}
| {
status: 'loading';
loading: true;
error: undefined;
result: undefined;
}
| {
status: 'success';
loading: false;
error: undefined;
result: R;
}
| {
status: 'error';
loading: false;
error: Error;
result: undefined;
};
type SetLoading<R> = (asyncState: AsyncState<R>) => AsyncState<R>;
type SetResult<R> = (result: R, asyncState: AsyncState<R>) => AsyncState<R>;
type SetError<R> = (error: Error, asyncState: AsyncState<R>) => AsyncState<R>;
Expand Down Expand Up @@ -135,7 +154,6 @@ const normalizeOptions = <R>(
type UseAsyncStateResult<R> = {
value: AsyncState<R>;
set: Dispatch<SetStateAction<AsyncState<R>>>;
merge: (value: Partial<AsyncState<R>>) => void;
reset: () => void;
setLoading: () => void;
setResult: (r: R) => void;
Expand Down Expand Up @@ -167,19 +185,9 @@ const useAsyncState = <R extends {}>(
[value, setValue]
);

const merge = useCallback(
(state: Partial<AsyncState<R>>) =>
setValue({
...value,
...state,
}),
[value, setValue]
);

return {
value,
set: setValue,
merge,
reset,
setLoading,
setResult,
Expand Down Expand Up @@ -217,7 +225,6 @@ export type UseAsyncReturn<
Args extends any[] = UnknownArgs
> = AsyncState<R> & {
set: (value: AsyncState<R>) => void;
merge: (value: Partial<AsyncState<R>>) => void;
reset: () => void;
execute: (...args: Args) => Promise<R>;
currentPromise: Promise<R> | null;
Expand Down Expand Up @@ -298,7 +305,6 @@ const useAsyncInternal = <R = UnknownResult, Args extends any[] = UnknownArgs>(
return {
...AsyncState.value,
set: AsyncState.set,
merge: AsyncState.merge,
reset: AsyncState.reset,
execute: executeAsyncOperationMemo,
currentPromise: CurrentPromise.get(),
Expand Down