brooksrelyt
brooksrelyt

Reputation: 4035

GraphQL returning no errors but undefined

Have been searching for a while. I am using Gatsby and I have no errors in the console or terminal but values are undefined. Could it be because of the second "data" under "articles"?

GraphiQL Query:

enter image description here

Query/Component Code:

import React, { Component } from 'react'
import { graphql } from 'gatsby'

// This query is executed at build time by Gatsby.
export const GatsbyQuery = graphql`
  {
    umdHub {
      articles {
        data {
          title
        }
      }
    }
  }
`

class ClientFetchingExample extends Component {
  render() {
    const {
      umdHub: { articles },
    } = this.props.data

    console.log(articles.title)
    return (
      <div style={{ textAlign: 'center', width: '600px', margin: '50px auto' }}>
        <h1>{articles.title} - Is the title of the article</h1>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
      </div>
    )
  }
}

export default ClientFetchingExample

Upvotes: 0

Views: 450

Answers (1)

Ashok
Ashok

Reputation: 2932

You already halfway there just small changes

const {
      umdHub: { articles },
    } = this.props.data

Now you have this articles object like this

articles: {
    data: [
        { 
          title: 'Learning to Listen'
        },
        { 
          title: 'Second Title'
        }
        ...
    ]
}

Now you need to loop over data

import _ from 'lodash'
const data = _.get(articles, 'data', [])

_.map(data, title => {
    console.log({ title })
})

If you want to only first title then

const title = _.get(articles, 'data[0].title', 'default value or blank string')

Here lodash is A modern JavaScript utility library delivering modularity, performance & extras.

Upvotes: 1

Related Questions