Skip to main content

On this page

Data Fetching

Overview

Data stored in Root CMS can be fetched on the server-side using the RootCMSClient. Data is typically fetched in either the route's getStaticProps() or handle() method. To initialize a RootCMSClient, pass it the rootConfig object, which is available from the route.

Example:

ts
// @/routes/[...page].tsx

import {Handler} from '@blinkk/root';
import {RootCMSClient} from '@blinkk/root-cms';

export const handle: Handler = async (req, res) => {
  const ctx = req.handlerContext;
  const pageSlug = ctx.params.page;
  const cmsClient = new RootCMSClient(req.rootConfig);
  const mode = String(req.query.preview) === 'true' ? 'draft' : 'published';
  const doc = await cmsClient.getDoc('Pages', pageSlug, {mode});
  if (!doc) {
    return ctx.render404();
  }
  const props = {slug, mode, doc};
  return ctx.render(props};
};

Listing Docs

To list docs in a collection, use the listDocs() method:

ts
const cmsClient = new RootCMSClient(req.rootConfig);
const mode = String(req.query.preview) === 'true' ? 'draft' : 'published';
const orderBy = mode === 'draft' ? 'sys.createdAt' : 'sys.firstPublishedAt';
const blogPosts = await cmsClient.listDocs('BlogPosts', {
  mode,
  orderBy,
  orderByDirection: 'desc',
});
1
2
3
4
5
6
7
8
9
10
11
12
Breakpoint: