Property 'prismic' of undefined

Hi prismic people, this is my first time building a small project using gatsby with gatsby-source-prismic-graphql . Queried all projects data from prismic inside my component but got

TypeError: Cannot read property ‘prismic’ of undefined

import React from 'react'
import { TiDelete } from 'react-icons/ti'
import { graphql } from 'gatsby'

const Nav = ({ props, project }) => (
  <>
    <div className="bg-black z-10 absolute inset-0">
      <div className="min-h-full nav-content p-24 text-white">
        <div className="flex justify-between md:ml-auto w-3/4 py-8 md:py-64 px-8 md:px-64">
          <ul>
            <li className="text-2xl mb-8">
              <a href="/" >Home</a>
            </li>
            <li className="text-2xl mb-8">
              <a href="/about">About</a>
            </li>

            <li className="text-2xl mb-8">
              <a href="/work">Work</a>
            </li>
          </ul>
        </div>
        <button onClick={props.onClick} className="text-white absolute top-0 right-0 my-4 mx-4">
          <TiDelete size={'2em'} />
        </button>
      </div>
    </div>
  </>
)

export default ({ data }) => {
  const project = data.prismic.allProjects.edges.slice(0, 1).pop()

  if (!project) return null

  return (
    <Nav project={project} />
  )
}

export const query = graphql`
  {
    prismic {
      allProjects {
        edges {
          node {
            project_title
            _meta {
              uid
            }
          }
        }
      }
    }
  }
`

Hey!

If you have configured the plugin to enable Previews you will need to add a validation just before saving and rendering the retrieved data. This check will prevent your application from breaking during the website build.

You’ll need to ensure that the retrieved data response is valid and if not, return null. This example shows how it can be done.

const prismicContent = data.prismic. allProjects.edges[0]
if (!prismicContent) return null

const project = prismicContent.node

Even if your project doesn’t use the Preview functionality, we recommend putting these validations in place. This way if enable Previews in the future, your components will be ready and your project won’t break on build.

Thanks for the advice, added preview on the plugin options but still no luck. same error

Cannot read property ‘prismic’ of undefined

Here’s my plugin setting

{
      resolve: 'gatsby-source-prismic-graphql',
      options: {
        repositoryName: process.env.REPO_NAME,
        accessToken: process.env.ACCESS_TOKEN,
        path: '/preview',
        previews: true,
        linkResolver: () => post => `/${post.uid}`,
      }
},

While digging in the Gatsby’s documentation, I found the answer to my question here. I wonder why my query isn’t working and realized that I am querying on a Nav component not a page.

StaticQuery solves the issue. Thanks again :sweat_smile: