Next.js Discord

Discord Forum

Do you use server actions to get data in client components?

Unanswered
Mini Satin posted this in #help-forum
Open in Discord
Mini SatinOP
I'm curious how members of this channel use server actions, specifically if you use server actions to fetch data inside client components.

- do you call them in SWR, ReactQuery or you use useTransition() hook?
- how do you transfer data and objects like Error from action to client component?

Any discussion and thoughts about server actions are welcome!

5 Replies

Dwarf Crocodile
You don't have to use server actions to do that, if you're running code from a server component you can just fetch an async function

server.ts
"use server";

const getData = async () => {
  return dataFromSomewhere;
}


page.tsx
"use server";

const Page = async() => {
  const data = await getData();

  return (
    <div>JSON.stringify(data)</div>
  )
}
oh nvm client components
I'd usually just pass data from a server component as a prop
so I can get the data on the server and then use it in the client without having to wait for data to load clientside
Catla
You can either pass through the data using props as @Dwarf Crocodile said, or you can set up an api route and fetch the data right from the client component using libraries like SWR.

I've not found a better way yet. I think prop drilling server fetched data to client pages is ridiculous, and something needs to be invented to fix it