UNPKG

next-safe-action

Version:

Type safe and validated Server Actions in your Next.js project.

74 lines (70 loc) 1.93 kB
"use client"; import "./errors-BsNXg-5Q.mjs"; import { n as getActionStatus, r as useActionCallbacks, t as getActionShorthandStatusObject, } from "./hooks-utils-DA2xDVWH.mjs"; import * as React from "react"; //#region src/stateful-hooks.ts /** * Use the stateful action from a Client Component via hook. Used for actions defined with [`stateAction`](https://next-safe-action.dev/docs/define-actions/instance-methods#action--stateaction). * @param safeActionFn The action function * @param utils Optional `initResult`, `permalink` and callbacks * @deprecated Directly use `useActionState` hook from `react` instead. * * {@link https://next-safe-action.dev/docs/execute-actions/hooks/usestateaction See docs for more information} */ const useStateAction = (safeActionFn, utils) => { const [result, dispatcher, isExecuting] = React.useActionState( safeActionFn, utils?.initResult ?? {}, utils?.permalink ); const [isIdle, setIsIdle] = React.useState(true); const [isTransitioning, startTransition] = React.useTransition(); const [clientInput, setClientInput] = React.useState(); const status = getActionStatus({ isExecuting, isTransitioning, result: result ?? {}, isIdle, hasNavigated: false, hasThrownError: false, }); const execute = React.useCallback( (input) => { setTimeout(() => { setIsIdle(false); setClientInput(input); }, 0); startTransition(() => { dispatcher(input); }); }, [dispatcher] ); useActionCallbacks({ result: result ?? {}, input: clientInput, status, cb: { onExecute: utils?.onExecute, onSuccess: utils?.onSuccess, onError: utils?.onError, onSettled: utils?.onSettled, }, navigationError: null, thrownError: null, }); return { execute, input: clientInput, result, status, ...getActionShorthandStatusObject(status), }; }; //#endregion export { useStateAction }; //# sourceMappingURL=stateful-hooks.mjs.map