| 1 | import { RegistryContext } from "@effect/atom-react"; |
| 2 | import { |
| 3 | type AtomCommand, |
| 4 | type AtomCommandOptions, |
| 5 | type AtomCommandResult, |
| 6 | runAtomCommand, |
| 7 | } from "@t3tools/client-runtime/state/runtime"; |
| 8 | import { useCallback, useContext } from "react"; |
| 9 | |
| 10 | export function useAtomCommand<A, E, W>( |
| 11 | command: AtomCommand<W, A, E>, |
| 12 | options?: string | AtomCommandOptions, |
| 13 | ): (value: W) => Promise<AtomCommandResult<A, E>> { |
| 14 | const registry = useContext(RegistryContext); |
| 15 | const label = typeof options === "string" ? options : (options?.label ?? command.label); |
| 16 | const reportFailure = typeof options === "string" ? true : (options?.reportFailure ?? true); |
| 17 | const reportDefect = typeof options === "string" ? true : (options?.reportDefect ?? true); |
| 18 | |
| 19 | return useCallback( |
| 20 | (value: W) => runAtomCommand(registry, command, value, { label, reportFailure, reportDefect }), |
| 21 | [command, label, registry, reportDefect, reportFailure], |
| 22 | ); |
| 23 | } |