NextJS component server side rendering with params injection from a caller component Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of NextJS component server side rendering with params injection from a caller component without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I am building an application with storefront, which uses nextJS. I am able to use getServerSide props while loading a new page.

The page contains many components, each needing their own data. At the moment, I am getting all of these into a results array and then returning from getServerSideProps, as shown below.

export async function getServerSideProps({query}) {
  let sid = query.shop

  let promises = []
  promises.push(getShopCategories(sid))
  promises.push(getShopInfo(sid))
  promises.push(offersFromShop(sid))

  try {

  let allPromises = Promise.all(promises)
  let results = await allPromises;

  //console.log("Shop Info:", results[1])
  return {props: {
      id: sid,
      shopCategories: results[0],
      shopInfo:  results[1],
      offers4u: results[2].products
  }}
  } catch(e) {
    console.error("Failure:", e)
    return { props: {}}
  }
}

But in this way, I have to get the data needed for all components in one shot. I was thinking, how to let each sub component in the page to have its own ‘getServerSideProps’. I can implement this in each component, but I am unsure about passing the parameters needed (such as shopId, productId etc., which I would have fetched in the main page).

One way is to use cookies, so that the server side can pick up these values. Is there a better solution?

Answer

getServerSideProps is only available on direct component under page folder

If you want to fetch more data on sub-component in the page, consider using the useEffect hook or componentDidMount for that work.

We are here to answer your question about NextJS component server side rendering with params injection from a caller component - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji