diff --git a/docs/docs/how-to/local-development/graphql-typegen.md b/docs/docs/how-to/local-development/graphql-typegen.md index 1a48bd7233d38..46172e1b69681 100644 --- a/docs/docs/how-to/local-development/graphql-typegen.md +++ b/docs/docs/how-to/local-development/graphql-typegen.md @@ -105,6 +105,54 @@ export const createSchemaCustomization: GatsbyNode["createSchemaCustomization"] Read the [Customizing the GraphQL schema guide](/docs/reference/graphql-data-layer/schema-customization/) to learn how to explicitly define types in your site or source plugin. +### GraphQL fragments + +Fragments allow you to reuse parts of GraphQL queries throughout your site and collocate specific parts of a query to individual files. Learn more about it in the [Using GraphQL fragments guide](/docs/reference/graphql-data-layer/using-graphql-fragments/). + +In the context of GraphQL Typegen fragments enable you to have individual TypeScript types for nested parts of your queries since each fragment will be its own TypeScript type. You then can use these types to e.g. type arguments of components consuming the GraphQL data. + +Here's an example (also used in [using-graphql-typegen](https://github.com/gatsbyjs/gatsby/tree/master/examples/using-graphql-typegen)) with a `Info` component that gets the `buildTime` as an argument. This `Info` component and its `SiteInformation` fragment is used in the `src/pages/index.tsx` file then: + +```tsx:title=src/components/info.tsx +import * as React from "react" +import { graphql } from "gatsby" + +// highlight-next-line +const Info = ({ buildTime }: { buildTime?: any }) => { + return ( +
+ Build time: {buildTime} +
+ ) +} + +export default Info + +// highlight-start +export const query = graphql` + fragment SiteInformation on Site { + buildTime + } +` +// highlight-end +``` + +```graphql:title=src/pages/index.tsx +# Rest of the page above... + +query IndexPage { + site { + ...SiteInformation + } +} +``` + +This way a `SiteInformationFragment` TypeScript type will be created that you can use in the `Info` component: + +```tsx:title=src/components/info.tsx +const Info = ({ buildTime }: { buildTime?: Queries.SiteInformationFragment["buildTime"] }) => {} +``` + ### Tips - When adding a new key to your GraphQL query you'll need to save the file before new TypeScript types are generated. The autogenerated files are only updated on file saves. diff --git a/examples/using-graphql-typegen/src/components/info.tsx b/examples/using-graphql-typegen/src/components/info.tsx index 2daf4617f9895..e078fdc91a934 100644 --- a/examples/using-graphql-typegen/src/components/info.tsx +++ b/examples/using-graphql-typegen/src/components/info.tsx @@ -1,8 +1,7 @@ import * as React from "react" import { graphql } from "gatsby" - -const Info = ({ buildTime }: { buildTime?: string | null }) => { +const Info = ({ buildTime }: { buildTime?: Queries.SiteInformationFragment["buildTime"] }) => { return (Build time: {buildTime}