Reputation: 188
I'm trying to use GraphQL fragments on a Gatsby site, I tried to follow guides to create this fragment but Gatsby throws an error stating that my fragment does not exist
The fragment "PageFragment" does not exist.
I located my fragment in a folder called "graphql-fragments" located in the root of the Gatsby project, this folder contains one file called "pageFragment.js" which is my fragment pageFragment.js
import { graphql } from "gatsby";
export const PageFragment = graphql`
fragment PageFragment on SanityPage {
slug {
current
}
_rawContent(resolveReferences: { maxDepth: 20 })
_id
title
}
`;
I use this fragment on my index page where I also get my error
import React from "react"
import { graphql } from "gatsby";
export const query = graphql`
query FrontpageQuery {
page: sanityPage(_id: { regex: "/(drafts.|)frontpage/" }) {
...PageFragment
}
}
`;
const Home = () => {
return (
<div>
Hello world
</div>
)
}
export default Home
Running the graphQL query without the fragment works fine, so this works and I am getting the data I expect
export const query = graphql`
query FrontpageQuery {
page: sanityPage(_id: { regex: "/(drafts.|)frontpage/" }) {
slug {
current
}
_rawContent(resolveReferences: { maxDepth: 20 })
_id
title
}
}
`;
It seems like Gatsby is not finding my fragment, any clues to what I'm doing wrong? Running on Gatsby version 2.24.66
Upvotes: 5
Views: 2603
Reputation: 969
Here is a quote from Gatsby docs:
To create a fragment, define it in a query and export it as a named export from any file Gatsby is aware of. A fragment is available for use in any other GraphQL query, regardless of its location in the project. Fragments are globally defined in a Gatsby project, so names have to be unique.
The file that export the fragment can not be stored in the root folder of the project where gatsby-config.js etc is located. If the Gatsby source files are in a folder called src
then the file that export the fragment has to be in the src
folder or one of its subfolders.
As a side note: one thing I sometimes forget is to add import { graphql } from "gatsby"
, but that's not the case here.
Upvotes: 3