Querying PortableText in Next.js with Sanity dataset and projectId
8 replies
Last updated: Feb 18, 2022
N
Hi, I am using
PortableTextbut I am wondering why is the dataset, projectId necessary when you hava projectId and dataset in the sanity.json file.
<PortableText dataset={process.env.NEXT_PUBLIC_SANITY_DATASET!} projectId={process.env.NEXT_PUBLIC_SANITY_PROJECT_ID!} content={post.body} serializers={{ h1: (props: any) => ( <h1 className="text-2xl font-bold my-5" {...props} /> ), h2: (props: any) => ( <h2 className="text-xl font-bold my-5" {...props} /> ), h3: (props: any) => ( <h3 className="text-lg font-bold my-5" {...props} /> ), h4: (props: any) => ( <h4 className="text-md font-bold my-5" {...props} /> ), blockquote: (props: any) => ( <blockquote className="text-xl text-red-300 font-bold my-5" {...props} /> ), li: ({ children }: any) => ( <li className="ml-4 list-disc">{children}</li> ), link: ({ href, children }: any) => ( <a href={href} className="text-blue-500 hover:underline"> {children} </a> ), }} />
Feb 18, 2022, 4:08 PM
N
Hi Geoff. So, the props for each serializer is not required? Good to know!
Feb 18, 2022, 8:09 PM
N
Good to know! Thanks
Feb 18, 2022, 8:11 PM
N
user A
Removing the {…props} from each serializer results in not being visible on the front-end side.Feb 18, 2022, 10:03 PM
You should be able to remove and .
dataset={process.env.NEXT_PUBLIC_SANITY_DATASET!}
projectId={process.env.NEXT_PUBLIC_SANITY_PROJECT_ID!}
Feb 18, 2022, 10:10 PM
N
user A
I’ve notice that when removing dataset and projectId there where I have one image inside the data body array Next js crashes. Because there is a image in the body of the Sanity article.Error: You must either:
- Pass
projectIdand
datasetto the block renderer
- Materialize images to include the
urlfield.
Feb 18, 2022, 10:15 PM
N
After removing the projectId and dataset it works if the post has no image in the body. But having only
bodyinside the query will cause Nextjs to crash. I’ve replaced it with the following and managed to fix the issue.
body[]{ ..., asset -> { ..., "_key": _id } },
user A
is that kind of a spread operator, and does the [] make it an array of content, where you pick the asset to display.Feb 18, 2022, 10:28 PM
Those props will be required in order to handle images unless you handle images in your serializer. Here’s one I’m using, for example:
types: { image: ({ node: { caption, credit, asset, alt, width } }) => ( <figure className="inline-image"> <img src={urlFor(asset).width(width).fit('max').url()} alt={alt} /> <figcaption> {caption && <span className="float-left">{caption}</span>} {credit && <i className="float-right">Photo credit: {credit}</i>} </figcaption> </figure> ), // ... other stuff ... }
Feb 18, 2022, 10:40 PM
Sanity– build remarkable experiences at scale
Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.