Search code examples
graphqlgatsby

Gatsby and GraphQL: query pdf file using <StaticQuery/>


I am very new to graphQL.

Inside src I have a data folder which contains a pdf named my_cv.pdf

Problem: I am unable to either load it in the browser or able to download it. I get an error There's not a page yet at /data.file.publicURL

gatsby.config.js

    {
      resolve: "gatsby-source-filesystem",
      options: {
        path: `${__dirname}/src/data/`,
        name: "data",
      },
    },

my hero component

this is inside the render() of the class component.

 <Resume href="data.file.publicURL" target="_blank">
    Download Resume
  </Resume>

this is how I am querying it.

<StaticQuery
    query={graphql`
      query {
        pdf: file(name: { eq: "my_cv.pdf" }) {
          name
          extension
          publicURL
        }
</StaticQuery>

Solution

  • The problem is that you are aliasing file as pdf, hence the nesting should be:

     <Resume href="data.pdf.publicURL" target="_blank">
        Download Resume
      </Resume>
    

    If you use StaticQuery I think you may want to use something like:

    import React from "react";
    import { StaticQuery, graphql } from "gatsby";
    
    export default function Header() {
      return (
        <StaticQuery
          query={graphql`
            query {
              pdf: file(name: { eq: "my_cv.pdf" }) {
                name
                extension
                publicURL
              }
            }
          `}
          render={(data) => (
            <Resume href="data.pdf.publicURL" target="_blank">
              Download Resume
            </Resume>
          )}
        />
      );
    }
    

    If you use useStaticQuery hook you can detach the logic from Resume of the StaticQuery component

    import React from "react";
    import { useStaticQuery, graphql } from "gatsby";
    
    export default function Header() {
      const data = useStaticQuery(graphql`
        query {
          pdf: file(name: { eq: "my_cv.pdf" }) {
            name
            extension
            publicURL
          }
        }
      `);
    
      return (
        <Resume href="data.pdf.publicURL" target="_blank">
          Download Resume
        </Resume>
      );
    }
    

    In both cases, be sure that the GraphQL query is returning valid data.