Trouble mapping GraphQL query to component in Gatsby

4 replies
Last updated: May 30, 2020
So haven't really worked with Sanity/Gatsby for a while but trying to get more into it recently, but right now I can't for the love of god get my query to work. I get it to work in the Gatsby/GraphQL playground thing, but I can't map it out in a component. Currently my code looks like (see below), and I get no console errors, but when I try to go into localhost:8000 I get the error "Cannot read property 'edges' of undefined". Any tips on how to fix?

import React, { useState } from "react"
import styled from "styled-components"
import { graphql } from "gatsby"

export const query = graphql`
  {
    allSanityProduct {
      edges {
        node {
          title
          sanityId
          description
        }
      }
    }
  }
`

const TestComponent = data => (
  <Box>
    <p>Test</p>
    <select name="product">
      {data.allSanityProduct.edges.map(({ node: product }) => (
        <option>{product.title}</option>
      ))}
    </select>
  </Box>
)

export default TestComponent

const Box = styled.div`
  padding-bottom: 100px;
  border-bottom: 2px dotted red;
`
May 30, 2020, 12:46 PM
What do you see if you log
data
to your console?
May 30, 2020, 2:16 PM
What do you see if you log
data
to your console?
May 30, 2020, 2:16 PM
Managed to fix it. Hadn't passed data down correctly from index
May 30, 2020, 2:24 PM
Glad to hear, Per, and thanks for sharing what the issue was ๐ŸŽ‰
May 30, 2020, 2:27 PM

Sanityโ€“ build remarkable experiences at scale

The Sanity Composable Content Cloud is the headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?