Replies: 1 comment
-
lazy internet, I asked AI for you! "use server";
import { auth } from "@/lib/auth";
import { PrismaClient } from "@prisma/client";
import { headers } from "next/headers";
import { redirect } from "next/navigation";
export async function reconfigureAction() {
// Get the session from request headers
const session = await auth.api.getSession({
headers: headers(),
});
if (!session) {
// When unauthorized, you can throw an error or redirect to a login page.
throw new Error("Unauthorized");
}
// Initialize your Prisma Client
const prisma = new PrismaClient();
// Update the user's onboarding flag
await prisma.user.update({
where: {
id: session.user.id,
},
data: {
onboarding: false,
},
});
// Perform the redirection on the server.
redirect("/dashboard/onboarding");
} "use client";
import { experimental_useFormStatus as useFormStatus } from "react-dom";
import { Button } from "@/components/ui/button";
import { reconfigureAction } from "@/app/actions/reconfigureAction";
export default function Account() {
const { pending } = useFormStatus();
async function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
event.preventDefault();
try {
// Call the server action. The redirect happens on the server,
// so the client will be navigated away automatically.
await reconfigureAction();
} catch (error) {
console.error("Error:", error);
// Optionally handle error state here
}
}
return (
<form onSubmit={handleSubmit} className="flex gap-2 flex-col">
<Button type="submit" variant="outline" disabled={pending}>
{pending ? "Configuring..." : "Reconfigure"}
</Button>
</form>
);
} AI generated codes, use at your own risk! |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Summary
Hello! I have decent knowledge in what I would call "basic react", but with more complex stuff like Server Rendering and Server Actions we get out of my comfort zone.
I have a client component where you can click "Reconfigure my profile" which calls an api that changes something on the bd. Once that returns, we redirect to a page. I was wondering, is there a way to turn that into a server action instead of creating an api route for it?
Additional information
Stripped down component :
API (app/api/onboarding/restart/route.ts)
Beta Was this translation helpful? Give feedback.
All reactions