Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing function from server to client component Next 13 [duplicate]

According to the Next.js docs for the app directory:

"Whenever possible, we recommend fetching data inside Server Components. Server Components always fetch data on the server."

This is great because I am hitting an external API (where I cannot change the CORS policy - Allow-Origins...).

I have a page (server component) with a form (client component), and I am trying to hit the API using the server component.

Home page

import Form from './Form';

export default function Home() {
   handleSubmit = () => {...submit logic}
   return <Form onSubmit={handleSubmit} />
}

Form Component

'use client'

export default function Form({ onSubmit }) {
 return <form onSubmit={handleSubmit}>...</form>
}

When I try to pass the handleSubmit function to the client component, I get this error:

Functions cannot be passed directly to Client Components because they're not serializable.

  1. I'm not sure what that means.
  2. Is there a way to pass functions to client components?
  3. I need to fetch from a server component because the API has CORS policy. Is it possible to do what I am trying to accomplish?

1 Answers

Do you have any error.js in your directory? Add use client at the top of the file.

See reference here: https://github.com/vercel/next.js/issues/42408 https://beta.nextjs.org/docs/rendering/server-and-client-components

Hope this helps.

like image 74
The-True-Hooha Avatar answered Mar 11 '26 09:03

The-True-Hooha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!