|
| 1 | +import { useCallback, useState } from 'react' |
| 2 | +import createHookError, { isAuthenticationCanceledError } from './error-utils' |
| 3 | +import { |
| 4 | + createHookFailureResult, |
| 5 | + type HookError, |
| 6 | + type HookFailureResult, |
| 7 | +} from './types' |
| 8 | +import useAsyncLifecycle from './useAsyncLifecycle' |
| 9 | + |
| 10 | +/** |
| 11 | + * Outcome of a {@link UseMutationResult.mutate} call. Successful runs include the resolved value; |
| 12 | + * failures carry a normalized {@link HookError}. |
| 13 | + */ |
| 14 | +export type MutationOutcome<T> = |
| 15 | + | { readonly success: true; readonly data: T } |
| 16 | + | HookFailureResult |
| 17 | + |
| 18 | +/** |
| 19 | + * Shared state contract surfaced by {@link useMutation}. Mirrors {@link VoidAsyncState} so that |
| 20 | + * mutation-driven hooks can spread it into their public result without translation. |
| 21 | + */ |
| 22 | +export interface UseMutationState { |
| 23 | + readonly error: HookError | null |
| 24 | + readonly isLoading: boolean |
| 25 | + readonly isPending: boolean |
| 26 | +} |
| 27 | + |
| 28 | +/** |
| 29 | + * Options accepted on a per-call basis to customise error reporting. |
| 30 | + */ |
| 31 | +export interface MutateCallOptions { |
| 32 | + readonly operation?: string |
| 33 | + readonly hint?: string |
| 34 | +} |
| 35 | + |
| 36 | +export interface UseMutationResult extends UseMutationState { |
| 37 | + /** |
| 38 | + * Runs an imperative async procedure and tracks loading + error state. Auth-cancel |
| 39 | + * errors are silently absorbed (no error surfaced) but still produce a failure outcome |
| 40 | + * so callers can short-circuit their own UI flow. |
| 41 | + */ |
| 42 | + readonly mutate: <T>( |
| 43 | + fn: (signal: AbortSignal) => Promise<T>, |
| 44 | + options?: MutateCallOptions |
| 45 | + ) => Promise<MutationOutcome<T>> |
| 46 | + /** Clears the current error without otherwise touching state. */ |
| 47 | + readonly clearError: () => void |
| 48 | +} |
| 49 | + |
| 50 | +const IDLE: UseMutationState = { |
| 51 | + error: null, |
| 52 | + isLoading: false, |
| 53 | + isPending: false, |
| 54 | +} |
| 55 | + |
| 56 | +/** |
| 57 | + * Generic state-machine + abort wiring shared by every mutation-style hook (`useSecureOperation`, |
| 58 | + * `useKeyRotation`, plus the `saveSecret`/`removeSecret`/`clearAll` helpers in |
| 59 | + * `useSecureStorage`). Centralises the auth-cancel / mount-guard / abort logic so each consumer |
| 60 | + * can stay a thin wrapper. |
| 61 | + * |
| 62 | + * @internal |
| 63 | + */ |
| 64 | +const useMutation = ( |
| 65 | + defaultOperation: string, |
| 66 | + defaultHint: string |
| 67 | +): UseMutationResult => { |
| 68 | + const [state, setState] = useState<UseMutationState>(IDLE) |
| 69 | + const { begin, mountedRef } = useAsyncLifecycle() |
| 70 | + |
| 71 | + const mutate = useCallback( |
| 72 | + async <T>( |
| 73 | + fn: (signal: AbortSignal) => Promise<T>, |
| 74 | + options?: MutateCallOptions |
| 75 | + ): Promise<MutationOutcome<T>> => { |
| 76 | + const operation = options?.operation ?? defaultOperation |
| 77 | + const hint = options?.hint ?? defaultHint |
| 78 | + const controller = begin() |
| 79 | + |
| 80 | + setState({ error: null, isLoading: true, isPending: true }) |
| 81 | + |
| 82 | + try { |
| 83 | + const data = await fn(controller.signal) |
| 84 | + if (mountedRef.current && !controller.signal.aborted) { |
| 85 | + setState(IDLE) |
| 86 | + } |
| 87 | + return { success: true, data } |
| 88 | + } catch (errorLike) { |
| 89 | + const hookError = createHookError(operation, errorLike, hint) |
| 90 | + if (!mountedRef.current || controller.signal.aborted) { |
| 91 | + return createHookFailureResult(hookError) |
| 92 | + } |
| 93 | + if (isAuthenticationCanceledError(errorLike)) { |
| 94 | + setState(IDLE) |
| 95 | + } else { |
| 96 | + setState({ error: hookError, isLoading: false, isPending: false }) |
| 97 | + } |
| 98 | + return createHookFailureResult(hookError) |
| 99 | + } |
| 100 | + }, |
| 101 | + [begin, mountedRef, defaultOperation, defaultHint] |
| 102 | + ) |
| 103 | + |
| 104 | + const clearError = useCallback(() => { |
| 105 | + setState((prev) => (prev.error ? { ...prev, error: null } : prev)) |
| 106 | + }, []) |
| 107 | + |
| 108 | + return { ...state, mutate, clearError } |
| 109 | +} |
| 110 | + |
| 111 | +export default useMutation |
0 commit comments