Toast on success w/ server action + useActionState()
#67660
Replies: 6 comments 8 replies
-
I would have said to use something like |
Beta Was this translation helpful? Give feedback.
-
Yeah.. anybody know how can I run a client side function after successful server action, if useActionState doesnt return anything different on success? |
Beta Was this translation helpful? Give feedback.
-
Here is my personal example, with zod client/server validation, loading state, and error/success toasts (reset the form here if you want): |
Beta Was this translation helpful? Give feedback.
-
There are two ways to achieve it: If no useActionState is used, you can just await the promise. |
Beta Was this translation helpful? Give feedback.
-
There seem to be lots of confusing ways to do this, but I found this to be the simplest approach: Following the docs, you'll want to have an initial state: export const initialState = {
message: '',
success: false,
}; And normally, you'd likely just inline your action like this: const [state, action, pending] = useActionState(categoryAction, formData); But But when you want a client-side action to run, you likely want it to happen:
So the simplest way to do that is to create a wrapper function that captures the return from the server action, perform your client-side interaction, then return the result: So your code looks more like this: const [state, formAction] = useActionState(
async (_state: typeof initialState, formData: FormData) => {
const result = await categoryAction(formData);
if (result?.success) {
yourClientSideFn()
}
return result;
},
initialState
); as long as your I hope I understood what you asked and this helps. |
Beta Was this translation helpful? Give feedback.
-
so I tried a lot of code and that's my solution, i am not using useActionState but this code works fine function SubmitButton() {
const { pending } = useFormStatus()
return (
<Button disabled={pending}>
{ pending ? 'Adding...' : 'Add Todo' }
</Button>
)
}
export default function AddTodo() {
async function handleSubmit(formData: FormData) {
const { success, message } = await createTodo(formData)
if (success) toast.success(message)
else toast.error(message)
}
return (
<form action={handleSubmit} className="...">
{...}
<SubmitButton />
</form>
)
} |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Summary
Recommended way to achieve the following while using
useActionState()
and server actions?React.useEffect()
?Additional information
No response
Example
No response
Beta Was this translation helpful? Give feedback.
All reactions