# All files / src useAsyncAction.ts

100% Statements 200/200
100% Branches 6/6
100% Functions 1/1
100% Lines 200/200

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    2011x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    33x
    33x
    33x
    33x
    33x
    33x
    33x
    33x
    33x
    33x
    7x
    1x
    1x
    6x
    6x
    6x
    6x
    6x
    6x
    4x
    4x
    6x
    7x
    33x
    33x
    33x
    33x
    33x
    33x
    33x
    33x
    33x
    33x
     "use client";
    import { useCallback, useState } from "react";
    import type { NonNullRef, UseStateSetter } from "./types.js";
    import { useUnmounted } from "./useUnmounted.js";

    /**
     * @remarks \@since 6.0.0
     */
    export type AsyncActionFunction<Args extends unknown[]> = (
      ...args: Args
    ) => Promise<void>;

    /**
     * @remarks \@since 6.0.0
     */
    export type HandleAsyncAction = <Args extends unknown[]>(
      action: AsyncActionFunction<Args>
    ) => AsyncActionFunction<Args>;

    /**
     * @remarks \@since 6.0.0
     */
    export interface AsyncActionOptions {
      /** @defaultValue `false` */
      disabled?: boolean;
    }

    /**
     * @remarks \@since 6.0.0
     */
    export interface AsyncActionImplementation {
      pending: boolean;
      unmounted: NonNullRef<boolean>;
      setPending: UseStateSetter<boolean>;
      handleAsync: HandleAsyncAction;
    }

    /**
     * A simple utility hook for triggering a pending state while an async function
     * is running. This is really only useful if you aren't using something like
     * `react-query`, `@reduxjs/toolkit/query`, `@apollo/client`, etc for API calls
     * which have a built-in pending state for mutations.
     *
     * @example
     * Simple Example (Async Button)
     * ```tsx
     * import type { ButtonProps } from "@react-md/core";
     * import { box, Button, CircularProgress, useAsyncAction } from "@react-md/core";
     * import { cnb } from "cnbuilder";
     * import type { MouseEvent, ReactElement } from "react";
     *
     * import styles from "./AsyncButton.module.scss";
     *
     * export interface AsyncButtonProps extends ButtonProps {
     *   onClick(event: MouseEvent<HTMLButtonElement>): Promise<void>;
     * }
     *
     * export function AsyncButton(props: AsyncButtonProps): ReactElement {
     *   const { onClick, children, theme, className, disabled, ...remaining } = props;
     *   const { handleAsync, pending } = useAsyncAction({ disabled });
     *
     *   return (
     *     <Button
     *       {...remaining}
     *       aria-disabled={pending || undefined}
     *       disabled={disabled}
     *       className={cnb(pending && styles.loading, className)}
     *       theme={pending ? "disabled" : theme}
     *       onClick={handleAsync(onClick)}
     *     >
     *       {children}
     *       {pending && (
     *         <span
     *           className={box({
     *             align: "center",
     *             disablePadding: true,
     *             className: styles.overlay,
     *           })}
     *         >
     *           <CircularProgress />
     *         </span>
     *       )}
     *     </Button>
     *   );
     * }
     *
     * // `AsyncButton.module.scss`
     * // hide everything in the button except for the overlay containing the circular
     * // progress
     * .loading > *:not(.overlay) {
     *   opacity: 0;
     * }
     *
     * .overlay {
     *   border-radius: inherit;
     *   box-shadow: inherit;
     *   inset: 0;
     *   position: absolute;
     *   z-index: 1;
     * }
     * ```
     *
     * @example
     * Confirmation Dialog with Overlay
     * ```tsx
     * import {
     *   Button,
     *   DialogHeader,
     *   DialogContent,
     *   DialogFooter,
     *   Form,
     *   useAsyncAction,
     * } from "@react-md/core";
     * import CloseIcon from "@react-md/material-icons/CloseIcon";
     * import type { ReactElement } from "react";
     * import { useId } from "react";
     *
     * interface ExampleProps {
     *   hide(); void;
     *   submit(): Promise<void>
     * }
     *
     * function Example({ hide, submit }: ExampleProps): ReactElement {
     *   const { handleAsync, pending } = useAsyncAction();
     *   const formId = useId();
     *
     *   return (
     *     <>
     *       <DialogHeader>
     *         <DialogTitle>Some Title</DialogTitle>
     *         <Button aria-label="Close" onClick={hide} disabled={pending}>
     *           <CloseIcon />
     *         </Button>
     *       </DialogHeader>
     *       <DialogContent>
     *         <Form
     *           id={formId}
     *           onReset={hide}
     *           onSubmit={handleAsync(submit)}
     *         >
     *           // pretend content
     *         </Form>
     *       </DialogContent>
     *       <DialogFooter>
     *         <Button
     *           type="reset"
     *           form={formId}
     *           disabled={pending}
     *         >
     *           Cancel
     *         </Button>
     *         <Button
     *           type="submit"
     *           form={formId}
     *           disabled={pending}
     *         >
     *           Confirm
     *         </Button>
     *       </DialogFooter>
     *     </>
     *   );
     * }
     * ```
     *
     * @remarks \@since 6.0.0
     */
    export function useAsyncAction(
      options: AsyncActionOptions = {}
    ): AsyncActionImplementation {
      const { disabled } = options;

      const [pending, setPending] = useState(false);
      const unmounted = useUnmounted();

      const handleAsync = useCallback<HandleAsyncAction>(
        (action) =>
          async (...args) => {
            if (pending || disabled) {
              return;
            }

            setPending(true);
            try {
              await action(...args);
            } finally {
              if (!unmounted.current) {
                setPending(false);
              }
            }
          },
        [disabled, pending, unmounted]
      );

      return {
        pending,
        unmounted,
        setPending,
        handleAsync,
      };
    }