Getting Started With Gatsby.js - Part 3

in #utopian-io7 years ago (edited)

In this tutorial you will be Learning

  • Getting Data in Gatsby
  • GraphQl

Requirements

  • Node.js and NPM installed on your System
  • Know basics of HTML, CSS and JavaScript, though not mandatory

Difficulty

  • Intermediate

Tutorial Contents

We all know a website is made up of a lot of components and in that Data is one of the important component. Just think about Utopian.io without any posts, would it attract users, no it will not. So to make people come and enjoy any website by reading or doing something you need Data and this tutorial is about getting Data into Gatsby Site.

Now we talked about Data, what exactly is data. If I talked about Utopian.io, whatever posts we write are data because it is outside the Code base of Utopian thus its called a Data similarly whatever is outside of Gatsby Component are data. We will be bringing the data from outside and show it from the component whenever we need it. Data can be anywhere a file, database, through the API or even from the Wordpress.

Gatsby uses GraphQL to pull data from outside to the components. According to GraphQL.org

GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data. GraphQL provides a complete and understandable description of the data in your API, gives clients the power to ask for exactly what they need and nothing more, makes it easier to evolve APIs over time, and enables powerful developer tools.

In this tutorial we will be building a page which looks like below which gives the details about the Utopian Moderators. Now since the data is outside of React Components we need to have some mechanism of getting it.

image.png

We will be using a simple File System where all my moderator JSON response is kept. So to do that we have to install gatsby-source-filesystem and gatsby-transformer-json and then change the gatsby-config.js as below :

module.exports = {
  siteMetadata: {
    title: 'Utopian Moderator',
  },
  plugins: ['gatsby-plugin-react-helmet', 'gatsby-transformer-json', 'gatsby-plugin-glamor',
  {
      resolve: 'gatsby-source-filesystem',
      options: {
        name: 'src',
        path: 'Path of your file',
      },
  },
 ],
};

Now once done we have to write your GraphQL query. Whenever you start your Gatsby site you might have seen something like below where its written that GraphiQL is an in-browser IDE to explore site's data and schema which can be seen at http://localhost:8000/___graphql.

image.png

When you head over to the http://localhost:8000/___graphql you will see something like below where left hand side you will be writing the query and right hand side will give you the result of the query.

image.png

Since we already got teh data from Utopian API we will be writing the query as below where allSrcJson is the root entity and then we have edges and node. Inside node we get all the results of the moderators.

{
  allSrcJson {
      totalCount
      edges {
        node {
          total
          results {
            account
            total_paid_rewards
            should_receive_rewards
            total_moderated
            percentage_total_rewards_moderators
            supermoderator
            referrer
          }
        }
      }
   }
}

which gives the result as

image.png

Now once we get the GraphQL query, now its time to create the page which we have shown earlier. So to include the query in your Gatsby we just have to write our query inside IndexQuery with graphql tag. This graphql tag is provided by the Gatsby where in Gatsby Build Process the queries are parsed before using. We are also using the result in our component as data.allSrcJson.edges.map why because nodes is an array of objects where we need to get an object from the entire lists. Since in our case we have defined total moderators inside the node itself we can get that value using node.total. No again the results is an array of objects so we need to map that too and get the values out of it.

import React from "react"

export default ({ data }) => <div>
    <h1>Utopian Moderator</h1>
    {data.allSrcJson.edges.map(({ node }) => (
        <div key={node.total}>
          <p>Total Modeartors : {node.total}</p>
          {node.results.map(obj => {
            if (obj) {
                var value = Number(obj.percentage_total_rewards_moderators).toFixed(2);
                return <p>{obj.account} Moderator modearted {obj.total_moderated} posts 
                                who has Moderation Percentage of {value}% out of 100%</p>
            } else return null
          })}
        </div>
    ))}
</div>
    
export const query = graphql`
  query IndexQuery {
    allSrcJson {
      totalCount
      edges {
        node {
          total
          results {
            account
            total_paid_rewards
            should_receive_rewards
            total_moderated
            percentage_total_rewards_moderators
            supermoderator
            referrer
          }
        }
      }
    }
  }
`;

Curriculum



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

Thank you for the contribution. It has been approved.

You can contact us on Discord.
[utopian-moderator]

@codingdefined, Upvote for supporting you.

Hey @codingdefined I am @utopian-io. I have just upvoted you!

Achievements

  • Seems like you contribute quite often. AMAZING!

Community-Driven Witness!

I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!

mooncryption-utopian-witness-gif

Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x

Coin Marketplace

STEEM 0.17
TRX 0.16
JST 0.029
BTC 68911.49
ETH 2524.87
USDT 1.00
SBD 2.53