skip to Main Content

Got this error message in Next.js but have no idea what to do with this. Next.js version 13.0.5.

I was passing a prop to a client component in Next.js. Prop is the list of objects, and one of the values is a function. But the question is, what this error message means?

Error: Functions cannot be passed directly to Client Components unless you explicitly expose it by marking it with "use server"

How can I expose a function by marking it with "use server"?

matchesColumns.push({ field: 'pk', headerName: "", flex: 0.3, renderCell: (params, event) => (<Link href={`/matches/${encodeURIComponent(params.row.pk)}`}>Details</Link>) });
(...)
{<Tabela2 rows={matchesRows} columns={matchesColumns}/>}

2

Answers


  1. If using the error component in the application folder, please mention the first lines below code.

    "use client";

    The issue will definitely be resolved.

    Login or Signup to reply.
  2. This is a probably upcoming Next.js feature that however still kind of works.

    You can use server actions to pass async functions from server to client components while having them still be callable from client.

    Here’s an example:

    // page.tsx
    
    "use server";
    
    import { ClientComponent } from './ClientComponent.tsx';
    
    async function deleteItem(itemId: string) {
      "use server"; // mark function as a server action (fixes the error)
    
      // TODO add item deletion logic
      return null;
    }
    
    export function Page() {
      return <ClientComponent deleteItem={deleteItem} />
    }
    
    // ClientComponent.tsx
    
    export function ClientComponent({ deleteItem }) {
      return (
        <button onClick={async () => {
          await deleteItem("foobar");
          alert("item has been deleted");
        }}>
          delete item
        </button>
      );
    }
    

    I don’t think these are properly documented anywhere or officially supported, so proceed with caution.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search