Next.js Discord

Discord Forum

Fetch data and useState in the same component

Unanswered
Pacific herring posted this in #help-forum
Open in Discord
Avatar
Pacific herringOP
I am confused about something. I am using fetch to grab some data and setting that data as a state object. However, I need to make this a client component to use useState but cant do server actions with a client component. Whats the best way of achieving this?

15 Replies

Avatar
you can use server actions on client components, you just have to import it from a separate file with "use server" directive at the top of it
https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations#client-components
Avatar
Fetch the data in a parent server component, pass the data or promise down to the client component to consume.
Avatar
Pacific herringOP
hmm alright let me try that
seems server actions are for like form actions? not to fetch things on load right?
Avatar
African Slender-snouted Crocodile
The impression I got from React docs is that you can fetch, but you probably shouldn't.
They just renamed (or recategorised?) Server Actions to Functions (https://19.react.dev/reference/rsc/server-functions#noun-labs-1201738-(2)) but a twitter (X) post seemed to say this is to allow a wider range of server functions in future (not just form actions). See e.g. https://x.com/rwieruch/status/1841145065579610509?t=gh_WFX3kcNaMwfYkVK3oEw&s=19, https://x.com/feedthejim/status/1840810314302189901?t=Yi3_w3rBvdltC8JMV9lqcw&s=19
Avatar
server actions are mutations, so onClick, form submittions etc.
Dont fetch from it, since server actions expose POST endpoints so mismatch of conventions.

Just fetch in an rsc and pass it down as props.
Avatar
Pacific herringOP
these things are so confusing.. so is that what route.ts files are for? my biggest confusion is that there are so many ways of doing things
Avatar
its not that bad
Route handlers are everything, Dont use server actions, use just route handlers and its still going to work out amazingly
Route handlers are just api routes, the things we have always been writing
Server Actions are the new things, which are just POST route handlers being made by nextjs for you
it gives minor benefits and drawbacks
Benefits:
1) Its a function so its much easier to read and use
2) Revalidating with a server action instantly refreshes the cache in one network request


Drawbacks
1) It cant be used in parallel.. so multiple server actions called always run sequentially.
2) Its a POST endpoint so dont do random shit with it
thats it
Server Actions are just dx improvements to POST Route Handlers
Avatar
@Pacific herring if your questions are solved, please mark an answer