Query by UID

Thanks to the lifecycle hooks that we've created for using Slice Machine with Next.js it's really simple to query a document by it's UID.

Passing the UID manually

In the example below we have a file called test.js where we we import the useGetStaticProps method from next-slicezone/hooks. Then we manually enter the UID for the document inside the useGetStaticProps function and this function does the query for us. We then pass the props to the slice-zone component.

import { Client } from '../prismic'
import SliceZone from 'next-slicezone'
import { useGetStaticProps } from 'next-slicezone/hooks'
import resolver from '../sm-resolver.js'

const Page = (props) => <SliceZone {...props} resolver={resolver} />

// Fetch content from prismic
export const getStaticProps = useGetStaticProps({
  client: Client(),
  uid: 'my-great-page'
})

export default Page

💡Querying different custom types.

This function manually defaults to the custom type of page, if we wanted to use another custom type we would simply pass the field type: 'my-new-type'.

Passing the UID dynamically

In the example below we have a file called [uid].js where we we import the useGetStaticProps & useGetStaticPaths methods from next-slicezone/hooks.

Then we get the UID for the document from the params and pass it inside the useGetStaticProps function and this queries the document data for us. We then pass the props to the slice-zone component.

To create the paths for the Next.js project to build the pages we use the useGetStaticPaths method, again we pass the UID from params to build that paths dynamically.

import { Client } from '../prismic'
import SliceZone from 'next-slicezone'
import { useGetStaticProps, useGetStaticPaths } from 'next-slicezone/hooks'
import resolver from '../sm-resolver.js'

const Page = (props) => <SliceZone {...props} resolver={resolver} />

// Fetch content from prismic
export const getStaticProps = useGetStaticProps({
  client: Client(),
  uid: ({ params }) => params.uid
})

export const getStaticPaths = useGetStaticPaths({
  client: Client(),
  type: 'page',
  fallback: true,// process.env.NODE_ENV === 'development',
  formatPath: ({ uid }) => ({ params: { uid }})
})

export default Page

💡Single Types

The useGetStaticProps defaults to querying by repeatable types, you can learn how to query singeltons here.

9 Rue de la Pierre Levée, 75011 Paris