Next.js Discord

Discord Forum

Passing function from. Server to client component memt

Answered
Giant panda posted this in #help-forum
Open in Discord
Giant pandaOP
If I have a function or a class in a server component, and want to call the function in a client component, how do I go about it.

Passing it as props won't work
Is there a work around this?
Answered by !=tgt
so for example
"use server";
import { db, item, type InsertItemSchema } from "@/lib/db";
export async function addItemAction(data: InsertItemSchema) {
  await db.insert(item).values(data)
}


this would work in a client component
View full answer

16 Replies

@!=tgt what are you trying to do?
Giant pandaOP
I'm kinda building a library
@!=tgt a server component is a react component
Giant pandaOP
A client component is also a react component
@!=tgt a server component is a react component
Giant pandaOP
I want to try using server actions to see if it'll work
i see
so
you can use any file with the "use server" directive
in a client
or server component
so for example
"use server";
import { db, item, type InsertItemSchema } from "@/lib/db";
export async function addItemAction(data: InsertItemSchema) {
  await db.insert(item).values(data)
}


this would work in a client component
Answer
Giant pandaOP
Thank you
@Giant panda Thank you
be sure to mark the answer as the solution by right clicking on the message
Giant pandaOP
Okay