useAction()
info
useAction()
waits for the action to finish execution before returning the result. If you need to perform optimistic updates, use useOptimisticAction()
instead.
With this hook, you get full control of the action execution flow. Let's say, for instance, you want to change what's displayed by a component when a button is clicked.
Example
- Define a new action called
greetUser()
, that takes a name as input and returns a greeting:
"use server";
const inputSchema = z.object({
name: z.string(),
});
export const greetUser = actionClient
.inputSchema(inputSchema)
.action(async ({ parsedInput: { name } }) => {
return { message: `Hello ${name}!` };
});
- In your Client Component, you can use it like this:
"use client";
import { useAction } from "next-safe-action/hooks";
import { greetUser } from "@/app/greet-action";
export default function Greet() {
const [name, setName] = useState("");
const { execute, result } = useAction(greetUser);
return (
<div>
<input type="text" onChange={(e) => setName(e.target.value)} />
<button
onClick={() => {
execute({ name });
}}>
Greet user
</button>
{result.data?.message ? <p>{result.data.message}</p> : null}
</div>
);
}
As you can see, here we display a greet message after the action is performed, if it succeeds.
useAction()
arguments
safeActionFn
: the safe action that will be called viaexecute()
orexecuteAsync()
functions.utils?
: object with callbacks.
useAction()
return object
execute()
: an action caller with no return. Input is the same as the safe action you passed to the hook.executeAsync()
: an action caller that returns a promise with the return value of the safe action. Input is the same as the safe action you passed to the hook.input
: the input passed to theexecute()
orexecuteAsync()
function.result
: result of the action after its execution.reset()
: programmatically reset execution state (input
,status
andresult
).status
: string that represents the current action status.isIdle
: true if the action status isidle
.isTransitioning
: true if the transition status from theuseTransition
hook used under the hood istrue
.isExecuting
: true if the action status isexecuting
.isPending
: same asisExecuting
(deprecated).hasSucceeded
: true if the action status ishasSucceeded
.hasErrored
: true if the action status ishasErrored
.hasNavigated
: true if anext/navigation
function was called inside the action.
The executing
status and isExecuting
shorthand property include the transition state.
Explore a working example here.