Gatsby: data is "undefined" by graphql gatsby

Created on 24 Apr 2018  路  14Comments  路  Source: gatsbyjs/gatsby

I am using graphql for querying. query is not running in my code. but on graphql it is working fine.
Heres my files
package.json

{
    "gatsby": "latest",
    "gatsby-link": "latest",
    "gatsby-source-filesystem": "latest",
    "gatsby-transformer-remark": "^1.7.40",
    "react-helmet": "5.0.3",
}

gatsby-node.js
exports.createLayouts = async ({
  boundActionCreators
}) => {
  const {
    createLayout
  } = boundActionCreators;
  const token = await sakeAuth.credentials.getToken();
  const options = {
    headers: {
      Authorization: `Bearer ${token.accessToken}`
    }
  };
exports.onCreateNode = ({ node, getNode, boundActionCreators }) => {
  const { createNodeField } = boundActionCreators;
  // console.log(node.internal.type);
  if (node.internal.type === `FaqsJson`) {
    const slug = createFilePath({ node, getNode, basePath: `pages` });
    console.log("==========>", slug);
    createNodeField({
      node,
      name: `slug`,
      value: slug
    });
  }
};

exports.createPages = ({
  graphql,
  boundActionCreators
}) => {
  return new Promise(resolve => {
    graphql(`
    {
      allFaqsJson {
        edges {
          node {
            fields {
              slug
            }
          }
        }
      }
    }
    `).then(result => {
        const { createPage } = boundActionCreators;
        console.log("result=================>", result.data.allFaqsJson);
        result.data.allFaqsJson.edges.forEach(({ node }) => {
          console.log(`create page for=========> ${node.fields.slug}`);
          createPage({
            path: node.fields.slug,
            component: path.resolve(`./src/templates/faqs.tsx`),
            context: {
              // Data passed to context is available in page queries as GraphQL variables.
              slug: node.fields.slug
            }
          });
        });
        resolve();
      });
  });
};

in src/templates/faqs.tsx

import { css, merge } from "glamor";
import * as React from "react";
import { InjectedIntlProps, injectIntl } from "react-intl";
interface OwnProps extends React.HTMLProps<HTMLDivElement> {
  styles?: React.CSSProperties;
}

interface State { }

type Props = OwnProps & InjectedIntlProps;

class Faqs extends React.Component<Props, State> {

  constructor(props: Props) {
    super(props);
  }
  public componentDidMount() {
    const { data } = this.props;
    console.log("===>>>>", data); // Here data is undefined :-(
  }
  public render() {
    const { data } = this.props;
    console.log("template", data); // Here data is undefined :-(
    return (
      <div>
        faqs
      </div>
    );
  }

}

export const query = graphql`
  query fqlQuery($slug: String!) {
    allFile {
      edges{
        node{
          childFaqsJson{
            title
          }
        }
      }
    }
  }
`;

export default injectIntl(Faqs);

in .cache/json
faqs.json file is not creating.
Can any body help in it?

question or discussion

Most helpful comment

OKAY so I figured out what my problem was and I don't know if this will apply to @Neha-takhi-cipl

My query worked when I put it in a component in the pages folder. I then fed the props into the component I needed the images in. Originally, it was just a regular component.

All 14 comments

You would need to format your code properly using the

github markdown syntax

So your code gets a little understandable.

@Jaikant done with code formatting

Are you sure your query is correct?

It has a childFaqsJson inside of allFile, I have only seen generic formats like remark, images, json, yaml within allFile.

{
    allFile {
      edges{
        node{
          childFaqsJson{
            title
          }
        }
      }
    }
  }

graphqlres
See Result is coming

You are probably using gatsby-transformer-json, which is creating these FaqsJSON.

There could be some error happening prior which is causing the query to fail. I am unable to say what it could be, with the information available.

Yes, we are using gatsby-transformer-json. can you please tell, what i am missing?
Apart form above code, in gatsby-config.js

module.exports = {
  siteMetadata: {
    title: `My website`
  },
  plugins: [
    // Parse all images files
    // `gatsby-transformer-sharp`,
    // `gatsby-plugin-sharp`,
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `data`,
        path: `${__dirname}/data`
      }
    },
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `data`,
        path: `${__dirname}/src/templates`
      }
    },
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `data`,
        path: `${__dirname}/src/pages`
      }
    },

    // Parse JSON files
    `gatsby-transformer-json`,

    // Yoursite.com/about/ becomes yoursite.com/about
    `gatsby-plugin-remove-trailing-slashes`,

    // Add typescript stack into webpack
    `gatsby-plugin-typescript`,

    // This plugin takes your configuration and generates a
    // web manifest file so your website can be added to your
    // homescreen on Android.
    /* eslint-disable camelcase */
    {
      resolve: `gatsby-plugin-manifest`,
      options: {
        name: `Gatsby website`,
        short_name: `Gatsby website`,
        start_url: `/`,
        background_color: `#f7f7f7`,
        theme_color: `#191919`,
        display: `minimal-ui`
      }
    },
    /* eslint-enable camelcase */
    // `gatsby-plugin-catch-links`,
    // This plugin generates a service worker and AppShell
    // html file so the site works offline and is otherwise
    // resistant to bad networks. Works with almost any
    // site!
    // `gatsby-plugin-offline`,
    {
      resolve: `gatsby-plugin-typography`,
      options: {
        pathToConfigModule: `src/theme/Typography.ts`
      }
    },
    {
      resolve: 'gatsby-transformer-remark',
      options: {
        plugins: [] // Just in case those previously mentioned remark plugins sound cool :)
      }
    }
  ]
};

I had a similar issue where on GraphiQL the query worked and I could find the data but the data wasnt being passed on to the component props.

Here's my file with the query:

import React from 'react';
import styled from 'styled-components';
import Img from 'gatsby-image';

import StyledHeader from '../styled-components/home-hero';
import heroImage from '../images/hero-mobile.jpg';

const Circle = styled.div`
  position: relative;
  z-index: 5;
  transform: translateZ(0);
  width: 200px;
  height: 200px;
  border-radius: 50%;
  background-color: white;
  mix-blend-mode: overlay;
`

class Hero extends React.Component {
  render(){
    return (
      <StyledHeader>
        <Circle></Circle>
        <p>Some text</p>
      </StyledHeader>
    );
  }
}

export default Hero;

export const query = graphql`
  query HeroImageQuery {
    imageSharp( id: { regex: "/hero-mobile/" }) {
      sizes(maxWidth: 960) {
        ...GatsbyImageSharpSizes_withWebp_tracedSVG
      }
    }
  }
`

My gatsby-config:

module.exports = {
  siteMetadata: {
    title: '',
  },
  plugins: [
    'gatsby-plugin-react-helmet',
    'gatsby-plugin-react-next',
    'gatsby-transformer-sharp',
    'gatsby-plugin-sharp',
    'gatsby-plugin-styled-components',
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `src`,
        path: `${__dirname}/src/`,
      },
    },
  ],
}

and a screenshot of graphiQL:
image

I kept getting errors when I passed this.props.data.imageSharp.sizes saying data was undefined. I checked out the component with React dev tools and sure enough, no props. I've been following along with the code on this page: https://using-gatsby-image.gatsbyjs.org/traced-svg/

OKAY so I figured out what my problem was and I don't know if this will apply to @Neha-takhi-cipl

My query worked when I put it in a component in the pages folder. I then fed the props into the component I needed the images in. Originally, it was just a regular component.

I am also experiencing the same situation. The data from the graphql query is showing as undefined. Did anyone else have a solution to this?

When I query the data using the GraphiQl tab, the data pulls correctly.

I'm just going to post this for other silly mistakes like mine. Mine query shows undefined because it was in the components folder. When I did the query in Layouts or Pages it worked perfectly.

Note: It also worked perfectly in GraphiQL

Sorry for being late to the party but the issue you are encountering has to do with the term we call page queries.

When your component is inside the pages or layout directory we execute your data and inject it inside the component. Whenever you move your component to another directory like components you're including your component inside a page and you have to use graphql fragments or StaticQuery.

Fragments are useful when you want to include your query inside the page query so only one graphql query is done to the server and is most likely what you want.

Sometimes you are dependant on props and you need to do an extra graphql query which you can do by using staticQuery which makes it possible to do graphql queries from inside your component.

@wardpeet, will be good put that in page-query docs.
https://www.gatsbyjs.org/docs/page-query/

OKAY so I figured out what my problem was and I don't know if this will apply to @Neha-takhi-cipl

My query worked when I put it in a component in the pages folder. I then fed the props into the component I needed the images in. Originally, it was just a regular component.

How do you send it down to a component trough a property of the component? is not clear how can I make a query from a component? I guess you can make dumb components and pass the data, that sounds good to me... to answer my own question jajajaja

Is this the same for

I have the same issue, but with a StaticQuery.
(I assume not), but tried

Was this page helpful?
0 / 5 - 0 ratings

Related issues

jimfilippou picture jimfilippou  路  3Comments

KyleAMathews picture KyleAMathews  路  3Comments

Oppenheimer1 picture Oppenheimer1  路  3Comments

ferMartz picture ferMartz  路  3Comments

theduke picture theduke  路  3Comments