Next.js Discord

Discord Forum

How to add a quantity selector to a page that is a serverside component

Answered
cnow posted this in #help-forum
Open in Discord
Hi, I have a page for individual products on my ecommerce site that i am building in next js, which displays a product given a ID in the URL. I thought that using SSG would be effective for this, however i am running into a problem. I want to implement a quantity selector on this page, but I can't use useState within a server-side component and if i make a seperate client component just for the quantity selector im not sure how to pass the data back to the parent component or if it is good practice to do so. What should i do?
Answered by cnow
i had another idea in mind, would this be a good solution?

Have one file page.tsx where i fetch the data using a server side component

then another file pageClient.tsx which has basically the whole page, so in page.tsx i would fetch the data then return something like <pageClient data={data}/> so that way everything is rendered client side but the data is fetched pre-render and is fetched on the server
View full answer

10 Replies

once the quantity is changed
@cnow Will this cause everything on the page to be re-rendered though?
you can use this structure

app/.../
  your-page/
    layout.tsx
    page.tsx

in the layout, put the things that don't depend on the query
only the things that depend on the query go to the page file

then when you use search params like the above, only the page is rerendered, the layout is intact
@cnow is there a way to do this other than using search params?
if you want to do querying in server components, you can only put data to it in a few ways: the url (which includes the search params), http headers such as by cookies

the conventional method is by search params
@joulev if you want to do querying in server components, you can only put data to it in a few ways: the url (which includes the search params), http headers such as by cookies the conventional method is by search params
i had another idea in mind, would this be a good solution?

Have one file page.tsx where i fetch the data using a server side component

then another file pageClient.tsx which has basically the whole page, so in page.tsx i would fetch the data then return something like <pageClient data={data}/> so that way everything is rendered client side but the data is fetched pre-render and is fetched on the server
Answer