How to get data from server action

So I'm trying to get data back from a server action, like you would in Remix with useActionData and I just don't know how to access it. As an example:
async function addUser(data: FormData) {
"use server"
const schema = zfd.formData({
name: z.string(),
})

try {
const { name } = schema.parse(data)
await db.insert(UsersTable).values({ name })
revalidatePath("/")
} catch (e: any) {
if (e instanceof ZodError) {
return { data: null, error: "There is an issue" }
} else {
throw e
}
}
}


export default async function NewUser() {
// How do I get this?
const stuffReturnedFromAction = idkWhat()

return (
<form action={addUser}>
<label htmlFor="name">First Name</label>
<input id="name" name="name" type="text" required />
<button type="submit" className="w-4 h-2 font-bold">
Add User
</button>
{/* to put it here */}
<p className="color-red">{stuffReturnedFromAction.error}</p>
</form>
)
}
async function addUser(data: FormData) {
"use server"
const schema = zfd.formData({
name: z.string(),
})

try {
const { name } = schema.parse(data)
await db.insert(UsersTable).values({ name })
revalidatePath("/")
} catch (e: any) {
if (e instanceof ZodError) {
return { data: null, error: "There is an issue" }
} else {
throw e
}
}
}


export default async function NewUser() {
// How do I get this?
const stuffReturnedFromAction = idkWhat()

return (
<form action={addUser}>
<label htmlFor="name">First Name</label>
<input id="name" name="name" type="text" required />
<button type="submit" className="w-4 h-2 font-bold">
Add User
</button>
{/* to put it here */}
<p className="color-red">{stuffReturnedFromAction.error}</p>
</form>
)
}
2 Replies
_ankri
_ankri2y ago
You can do
<form action={(formData) => {
const user = await createUser(formData);
console.log(user);
}}
>
</form>
<form action={(formData) => {
const user = await createUser(formData);
console.log(user);
}}
>
</form>
More info: https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions#props Or: https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions#experimental-useoptimistic (just ignore the optimistic stuff)
Data Fetching: Server Actions
Use Server Actions to mutate data in your Next.js application.
Kyle
KyleOP2y ago
sweet, thanks!
Want results from more Discord servers?
Add your server