0

I have an existing database served on postgres locally.

I'd like to fetch that data via GraphQL in my Gatsby app. I'm using gatsby-source-pg to do this.

It's not clear from the docs + example here how to set this up properly. From what I understand, you need the two highlighted portions below.

// ./src/components/test.js

import { graphql } from 'gatsby';
    
export const query = graphql` // (1) graphQL query
  {
    postgres {
      allUsers {
        nodes {
          id
          firstLastName
        }
      }
    }
  }
`;

const Test = ({data}) => { // (2) grab the `data` prop (not sure where this comes from)  
  return (
    <AppLayout>
      {data.postgres.allUsers.nodes.map(user => <p>{user.firstLastName}</p>)} // data is undefined
    </AppLayout>
  )
}

export default Test
// gatsby-config.js
    {
      resolve: "gatsby-source-pg",
      options: {
        connectionString: "postgres://user@localhost:5432/testdb",
        schema: "public",
      },
    },
Questions:
  • How do I query data from the ./src/components directory? The data prop returns undefined if I run the exact code above. I noticed this same setup works when running it from ./src/pages/index.js. Maybe I'm missing options parameter in gatsby-source-pg to tell it which directories to look at?
  • How is query and data from the code above connected? I couldn't tell by looking at the example.
Community
  • 1
  • 1
tbd_
  • 1,058
  • 1
  • 16
  • 39
  • 1
    That graphql will automatically run if it is exported from a page component (and the result added as a data prop). Since your `test` component is is in the `./src/components/` folder, it isn't getting run. – ksav Apr 06 '20 at 22:41
  • 1
    Alternatively, you could use a static query if you want to query in a non-page component. – ksav Apr 06 '20 at 22:44
  • 1
    @ksav Yes! This is what I was looking for, thank you :) – tbd_ Apr 06 '20 at 23:41

0 Answers0