0

I'm new to React and Gatsby. I'm trying to get data from a gatsby csv plugin in a component. I read that in components you have to use static query to get data but I can't make it works. I received "Cannot read property 'props' of undefined", so I think that I'm doing something wrong with the data constructor or maybe the syntax is wrong.

import React from 'react';
import { StaticQuery, graphql } from "gatsby"

const data = this.props.data.allLettersCsv.edges

export default () => (
  <StaticQuery
    query={graphql`
      query Corrispondences {
        allLettersCsv {
          edges {
            node {
              word
              value
            }
          }
        }
      }
    `}
    render={data.map((row,i) => (
        <div>
        <table>
          <thead>
            <tr>
              <th>Letter</th>
              <th>ASCII Value</th>
            </tr>
          </thead>
          <tbody>
              <tr key={`${row.node.value} ${i}`}>
                <td>{row.node.word}</td>
                <td>{row.node.value}</td>
              </tr>
          </tbody>
        </table>
      </div>
      ))
    }
  />
)

1 Answer 1

1

There are 2 problems in your code:

First, you are declaring data outside of component:

const data = this.props.data.allLettersCsv.edges

There is probably no this.props in the module scope, hence the error you get. You should remove this line, since gatsby provides graphql query results to your component via StaticQuery’s render.

Second, StaticQuery's render expect a function, where it passes the results from your graphql query as data (Checkout React's docs on render props).

So you could re-write it like this for example:

render={data => (
  <>
    {data.allLettersCsv.edges.map((row,i) => ...)}
  </>
)

Hope it helps!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.