Using Next.js Suspense with getServerSideProps for streaming response

38 views Asked by At

I have a react web page with next.js for SSR. My apis are all on firebase functions and I also use firebase functions (nextServer) to render my page on server side.

My actual problem is that when a user is navigated to my QuestionsAndAnswers page (or any other page with SSR), needs to wait till all the data is fetched and rendered on server side and received by client-side and this is actually an expected behavior and I'm looking for a way on client-side to render the parts already completed on server side and not the whole page at once. This way user will navigate much faster and via Suspense fallback, I can display skeletons for the parts which are not yet rendered.

When I read the following up-to-date documentations of Suspense and Streaming on next.js, I get the impression that it is possible to stream the already rendered data to client side in chunks and reduce the first content time. enter link description here enter link description here

I have tried so many things and my last try was using react use hook and pass the Promise function from getServerSideProps into my component via props and let use hook handle the result data as streaming.

export async function getServerSideProps(context) {
  const firebaseSingleton = FirebaseService.Instance;
  const functions = firebaseSingleton.Functions || {} as Functions;
  const getCategories = httpsCallable(functions, 'getCategories');
  var catMethod = getCategories().then((categoriesData: any) => {return 
   categoriesData.data});
  return {props:{catMethod}};
}

And my component code:

function QuestionsAndAnswers(props: { catMethod: any }) {
  let cache = new Map();
  function fetchData() {
    if (!cache.has(1)) {
      cache.set(1, props.catMethod);
    }
    return cache.get(1);
  }
  const categories: any = use(fetchData());

And when I try to pass props.catMethod directly into use or first cache it inide fetchData and passing fetchData into use hook throws similar errors:

H [Error]: Error serializing .catMethod returned from getServerSideProps in "/QuestionAndAnswers". Reason: object ("[object Promise]") cannot be serialized as JSON. Please only return JSON serializable data types.

I just want to know if I try to achieve something impossible? If not any help would be appreciated.

0

There are 0 answers