-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor(react): async action (#253)
- Loading branch information
Showing
5 changed files
with
120 additions
and
116 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
import { | ||
type AsyncValue, | ||
idle, | ||
MutationError, | ||
pending, | ||
} from "@reactive-dot/core"; | ||
import { useCallback, useState } from "react"; | ||
import type { Observable } from "rxjs"; | ||
|
||
/** | ||
* @internal | ||
*/ | ||
export function useAsyncAction< | ||
TArgs extends unknown[], | ||
TReturn extends Promise<unknown> | Observable<unknown>, | ||
>(action: (...args: TArgs) => TReturn) { | ||
type Value = | ||
TReturn extends Promise<infer Value> | ||
? Value | ||
: TReturn extends Observable<infer Value> | ||
? Value | ||
: never; | ||
|
||
const [state, setState] = useState<AsyncValue<Value, MutationError>>(idle); | ||
|
||
const execute = useCallback( | ||
(...args: TArgs) => { | ||
const resolve = (value: unknown) => setState(value as Value); | ||
|
||
const reject = (reason?: unknown) => setState(MutationError.from(reason)); | ||
|
||
try { | ||
setState(pending); | ||
|
||
const result = action(...args); | ||
|
||
if (result instanceof Promise) { | ||
return result.then(resolve).catch(reject); | ||
} else { | ||
return result.subscribe({ next: resolve, error: reject }); | ||
} | ||
} catch (error) { | ||
const mutationError = MutationError.from(error); | ||
setState(mutationError); | ||
throw mutationError; | ||
} | ||
}, | ||
[action, setState], | ||
); | ||
|
||
return [state, execute] as [state: typeof state, execute: typeof execute]; | ||
} |
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters