Search code examples
javascriptreactjsnext.jsstorefrontreact-redux-form

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


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?


Solution

  • 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.