Next.js Discord

Discord Forum

Server Action in client component error "use server" functions are not allowed in client components

Unanswered
Picardy Spaniel posted this in #help-forum
Open in Discord
Avatar
Picardy SpanielOP
I'm using NextJS 13.4. I follow along the docs here https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions#with-client-components.

i tried to create the action file first
// ./app/admin/menu/action.js
export async function addMenu(data) {
  "use server";
  console.log(data);
}

then i import in the client component
"use client";

import { useState } from "react";
import { addMenu } from "./action";

export function New(data) {
  const [isOpen, setOpen] = useState(false);

  return (
    <>
      <button onClick={setOpen}>Add New</button>
      <dialog open={isOpen}>
        <article>
          <h3>Add New Menu</h3>

          <form action={addMenu}>
          ...
          <button type="submit">Submit</button>
          </form>
        </article>
      </dialog>
    </>
  );
}


Then it thow an error saying "use server" functions are not allowed in client components. You can import them from a "use server" file instead.

I know it stated in the library that server component cannot be imported in the client component https://nextjs.org/docs/getting-started/react-essentials#unsupported-pattern-importing-server-components-into-client-components but the first docs i send said otherwise. I might doing things wrong here. So how do you use server action on client component?

1 Reply

Avatar
Picardy SpanielOP
oopps, i found whats wrong here. i should put the "use server" in the top level

"use server";
export async function addMenu(data) {
  console.log(data);
}