Docs
Query
Initial Query Data (SSR/SSG)

Initial Query Data (SSR/SSG)

Sometimes, we want to fetch our data on server-side, either doing it on every request (like Next.js' getServerSideProps) or at build-time (like Next.js' getStaticProps). We can populate the initial response data easily by utilizing setInitialResponse method. Note that this setInitialResponse method should be called on top of your component tree, or before any component invokes the hook (a.k.a subscribe the query).

// Single query
const usePopularProductQuery = createQuery(fetchPopularProduct);
const useProductDetailQuery = createQuery(fetchProductDetail); // With dynamic param
 
// Infinite query
const useNotificationsQuery = createQuery(
  (_, { pageParam }) => fetchNotifications(pageParam),
  { getNextPageParam: (lastPageResponse) => lastPageResponse.cursor },
);
 
export async function getServerSideProps() {
const popularProduct = await fetchPopularProduct();
const productDetail = await fetchProductDetail({ id: 3 });
const notifications = await fetchNotifications();
  return {
    props: {
      popularProduct,
      productDetail,
      notifications,
    }
  }
}
 
export default function Page({ popularProduct, productDetail, notifications }) {
  // The setInitialResponse method must be placed on the top or before any component subscribe to the query.
  // These setInitialResponse method will only run once.
  usePopularProductQuery.setInitialResponse({ response: popularProduct });
  useProductDetailQuery.setInitialResponse({ response: productDetail, key: { id: 3 } });
  useNotificationsQuery.setInitialResponse({ response: notifications, skipRevalidation: true });
  //                                                                  ^if we don't want to revalidate on client-side
 
  return <main> ... </main>
}