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 schema = z.object({
name: z.string(),
});
export const greetUser = actionClient
.schema(schema)
.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 viaexecuteorexecuteAsyncfunctions.utils?: object with optional base utils and 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 theexecuteorexecuteAsyncfunction.result: result of the action after its execution.reset: programmatically reset execution state (input,statusandresult).status: string that represents the current action status.isIdle: true if the action status isidle.isTransitioning: true if the transition status from theuseTransitionhook used under the hood istrue.isExecuting: true if the action status isexecuting.isPending: true if the action status isexecutingorisTransitioning.hasSucceeded: true if the action status ishasSucceeded.hasErrored: true if the action status ishasErrored.
For checking the action status, the recommended way is to use the isPending shorthand property. Using isExecuting or checking if status is "executing" could cause race conditions when using navigation functions, such as redirect.
Explore a working example here.