How to fetch data for Client Components on server-side
#63862
Replies: 2 comments
-
|
You are doing the right thing, the server component gets the data and the client component is responsible for handling the interaction logic, this is something you need to be aware of when using React Server Component, the two components divide the work to get better performance, maybe you just need to change your perception of switching from Pages routing to APP routing development model, I think you might need to learn the concept of RSC and you won't be this confused: |
Beta Was this translation helpful? Give feedback.
-
|
Even when you thought you were wrong at first and it was more like a question, you really helped me and actually explained it to me perfectly how I should do it as I also wanted to fetch data server side due to hiding secrets, but had to use that data for a button in a client component. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
When I say
Client Components-> I mean files that usesuse clientat the top of it, andServer Components— files that are usinguse serveraccordinglyNobody says, how to fetch data on the server side and pass it directly to the
Client Components(or I somehow didn't find that)Even more, —
async/awaitfunctions and components are forbidden inClient Components, and if you will try to fetch server data to prerender client components with it you will get an error:The NextJS documentation says that client-side fetch data should be handled in this way:
But this doesn't satisfy me at all, I want to get my data and fill the
client componentswith it on the server sidegetStaticProps/getServerSidePropsare also not available anymore, so...So, the solution that I got
App directory:
page.tsx
clientPage.tsx
So, NextJS provided to us a better way of handling server-side functions (I really like that we get rid of
getServerSideProps/getStaticProps), but now — I have to have two files:page.tsxfor a server logic andclientPage.tsxto provide all that logicAm I using that right?
Or I am missing something?
I am sorry for my English, but I hope, — you will get my point
P.S. If you will try to join this two files
page.tsxandclientPage.tsxinto one — you will get an error ("useState" is not allowed in Server Components.)Also if you will try to make something like this and use
Server ActionsinClient Componentsto fetch data on the server side to pre-render it:You will also get an error, because
Client Componentscan't useasync/awaittoawaitthe server actionOr, the other option that I thought of — maybe add
use clientto all thepage-componentsI mean,
/src/components/PartnersBut then the
App Routerbecome less comfortable, because I will need to create a one more joining compoennt, if I will need a few of them on the same pageBeta Was this translation helpful? Give feedback.
All reactions