Next.js Discord

Discord Forum

Server Action cannot be applied to client components-> DOCS example

Unanswered
Harlequin posted this in #help-forum
Open in Discord
Avatar
HarlequinOP
import DeployButton from "@/components/DeployButton";
import AuthButton from "@/components/AuthButton";
import { createClient } from "@/utils/supabase/server";
import Header from "@/components/Header";
import { redirect } from "next/navigation";

export default async function ProtectedPage() {
  const supabase = createClient();

  async function createTodo(formData: FormData) {
    "use server";
    const rawFormData = {
      name: formData.get("name"),
    };
    await supabase.from("todos").insert(rawFormData);
  }
  const {
    data: { user },
  } = await supabase.auth.getUser();

  // get all todos

  const { data: todos, error } = await supabase.from("todos").select("*");

  if (!user) {
    return redirect("/login");
  }

  return (
    <div className="flex-1 w-full flex flex-col gap-20 items-center">
      <div className="w-full">
        <div className="py-6 font-bold bg-purple-950 text-center">
          This is a protected page that you can only see as an authenticated
          user
        </div>
        <nav className="w-full flex justify-center border-b border-b-foreground/10 h-16">
          <div className="w-full max-w-4xl flex justify-between items-center p-3 text-sm">
            <DeployButton />
            <AuthButton />
          </div>
        </nav>
      </div>

      <div className="animate-in flex-1 flex flex-col gap-20 opacity-0 max-w-4xl px-3">
        <Header />
        <main className="flex-1 flex flex-col gap-6">
          <h2 className="font-bold text-4xl mb-4">Your todos</h2>

          <pre>{JSON.stringify(todos, null, 2)}</pre>
          <h1>Add a new todo</h1>
          <form action={createTodo}>
            <input type="text" name="name" />
            <button type="submit">Add</button>
          </form>
        </main>
      </div>
    </div>
  );
}
`

hey can anyone tell me what that errors out? it is more or less an example from the docs

1 Reply

Avatar
!=tgt
Move the function to another file for server actions, and at the top of that file, insert "use server" at the top. Then import the file in your client component