GatsbyJS getting data from Restful API

AJ- picture AJ- · Mar 15, 2018 · Viewed 23.7k times · Source

I am new in both React and GatsbyJS. I am confused and could not make figuring out in a simple way to load data from third-party Restful API.

For example, I would like to fetch data from randomuser.me/API and then be able to use the data in pages.

Let’s say something like this :

  import React from 'react'
  import Link from 'gatsby-link'

  class User extends React.Component {
    constructor(){
      super();
      this.state = {
        pictures:[],
      };

    }

    componentDidMount(){
      fetch('https://randomuser.me/api/?results=500')
      .then(results=>{
        return results.json();
      })
      .then(data=>{
        let pictures = data.results.map((pic,i)=>{
            return(
              <div key={i} >
                <img key={i} src={pic.picture.medium}/>
              </div>
            )
        })
        this.setState({pictures:pictures})
      })
    }

    render() {
      return (<div>{this.state.pictures}</div>)
    }
  }

  export default User;

But I would like to get the help of GraphQL in order to filter & sort users and etc…..

Could you please help me to find the sample to how I can fetch data and insert them into GraphQL on gatsby-node.js?

Answer

Nenu picture Nenu · Mar 16, 2018

If you want to use GraphQL to fetch your data, you have to create a sourceNode. The doc about creating a source plugin could help you.

Follow these steps to be able to query randomuser data with GraphQL in your Gatsby project.

1) Create nodes in gatsby-node.js

In your root project folder, add this code to gatsby-node.js:

const axios = require('axios');
const crypto = require('crypto');

exports.sourceNodes = async ({ boundActionCreators }) => {
  const { createNode } = boundActionCreators;

  // fetch raw data from the randomuser api
  const fetchRandomUser = () => axios.get(`https://randomuser.me/api/?results=500`);
  // await for results
  const res = await fetchRandomUser();

  // map into these results and create nodes
  res.data.results.map((user, i) => {
    // Create your node object
    const userNode = {
      // Required fields
      id: `${i}`,
      parent: `__SOURCE__`,
      internal: {
        type: `RandomUser`, // name of the graphQL query --> allRandomUser {}
        // contentDigest will be added just after
        // but it is required
      },
      children: [],

      // Other fields that you want to query with graphQl
      gender: user.gender,
      name: {
        title: user.name.title,
        first: user.name.first,
        last: user.name.last,
      },
      picture: {
        large: user.picture.large,
        medium: user.picture.medium,
        thumbnail: user.picture.thumbnail,
      }
      // etc...
    }

    // Get content digest of node. (Required field)
    const contentDigest = crypto
      .createHash(`md5`)
      .update(JSON.stringify(userNode))
      .digest(`hex`);
    // add it to userNode
    userNode.internal.contentDigest = contentDigest;

    // Create node with the gatsby createNode() API
    createNode(userNode);
  });

  return;
}

I used axios to fetch data so you will need to install it: npm install --save axios

Explanation:

The goal is to create each node for each piece of data you want to use. According to the createNode documentation, you have to provide an object with few required fields (id, parent, internal, children).

Once you get the results data from the randomuser API, you just need to create this node object and pass it to the createNode() function.

Here we map to the results as you wanted to get 500 random users https://randomuser.me/api/?results=500.

Create the userNode object with the required and wanted fields. You can add more fields depending on what data you will want to use in your app.

Just create the node with the createNode() function of the Gatsby API.

2) Query your data with GraphQL

Once you did that, run gatsby develop and go to http://localhost:8000/___graphql.

You can play with GraphQL to create your perfect query. As we named the internal.type of our node object 'RandomUser', we can query allRandomUser to get our data.

{
  allRandomUser {
    edges {
      node {
        gender
        name {
          title
          first
          last
        }
        picture {
          large
          medium
          thumbnail
        }
      }
    }
  }
}

3) Use this query in your Gatsby page

In your page, for instance src/pages/index.js, use the query and display your data:

import React from 'react'
import Link from 'gatsby-link'

const IndexPage = (props) => {
  const users = props.data.allRandomUser.edges;

  return (
    <div>
      {users.map((user, i) => {
        const userData = user.node;
        return (
          <div key={i}>
            <p>Name: {userData.name.first}</p>
            <img src={userData.picture.medium} />
          </div>
        )
      })}
    </div>
  );
};

export default IndexPage

export const query = graphql`
  query RandomUserQuery {
    allRandomUser {
      edges {
        node {
          gender
          name {
            title
            first
            last
          }
          picture {
            large
            medium
            thumbnail
          }
        }
      }
    }
  }
`;

That is it!