Next.js Discord

Discord Forum

Passing functions from server actions to client component error

Unanswered
Chartreux posted this in #help-forum
Open in Discord
ChartreuxOP
This is my code:

/utils/events.ts
import 'server-only'

 export const deleteEventById = 
  async (eventId: string) => {
    'use server'
    await delay()
    console.log(eventId)
    // await db.delete(events).where(eq(events.id, eventId))
  }


app/event/page.tsx
const Events = async () => {
  const user = await getCurrentUser()
  const events = await getAllEvents(user.id)

  return (
    <div>
      <EventList data={events} deleteEvent={deleteEventById} />
    </div>
  )
}


components/Eventlist.tsx
    <div>
      {data.map((event) => (
        <div key={event.id}>
          {event.name} <Link href={`/dashboard/events/${event.id}`}>Go To</Link>
          <Button onClick={() => handleClick(event.id)}>Edit</Button>
          <Button onClick={() => deleteEvent(event.id)}>Delete</Button>
        </div>
      ))}
    </div>


I'm encountered this error
Error: Functions cannot be passed directly to Client Components unless you explicitly expose it by marking it with "use server".


I'm new to next and that's my regular way to pass functions in react. My question is how can I pass the server function to client component?

5 Replies

@joulev put `"use server"` in `/utils/events.ts` to the top of the file
ChartreuxOP
using 'use server' does solve the function passing problem, but also creates a new problem.

If I use import 'server-only', the page updates the data automatically after I insert an item, but I can't delete it. If I use 'use server' , I can delete items, but somehow, after deletion, the item doesn't disappear automatically

This my getter function:
export const getAllEvents = memoize(
  async (userId: string) => {
    await delay()
    const data = await db.query.events.findMany({
      where: eq(events.createdById, userId),
    })
    return data
  },
  { persist: true, revalidateTags: () => ['events', 'dashboard:events'] }
)