GraphQL Tutorial - ReactJS Course: Lesson 1

by Anna Danilec

Intro to ReactJS with GraphQL

REST is an API design architecture, where requests are done through the URLs, and the core idea in the REST API is that when linking to a particular URL, you should get a piece of data, called a resource. Connecting to the URL in the REST API is called a request, and the answer is the response. 

GraphQL is a query language for the API. It allows us to ask for specific data, without calling the API a few times, and the request is done with queries. In case, developers need just one value from the database, there’s no need to get everything. GraphQL is organized as types and fields, not endpoints.

In past years REST was the standard in API architecture, but it wasn’t flexible enough to be comfortable in the rapidly changing requirements. To get more flexibility and efficiency, developers started to use GraphQL as a new standard for designing the API, in certain kinds of applications.

Some time ago, I showed you how to get and display data from the REST Api in ReactJS. In this article, I’d like to show you how to get data from GraphQL API to the React.js application using Axios. 

If you’d like to follow this tutorial, take a look at our ExpressJS course with GraphQL, which my friend did.

As always, for those who prefer watching tutorials then reading, here is the video version of this article.

Let’s start!

1. Create ReactJS app

Let’s start by creating a new ReactJS application, where we are going to build our project. For this open the terminal and use the following command.

npx create-react-app <app-name>

When the installation is finished, let’s start the application with this code:

cd <app-name>
yarn start

It should run at localhost:3000, and you should see the standard screen of the ReactJS application. 

2. Install Axios and add proxy

Now, it’s time to install the axios library, which we will use for our GraphQL request. Let’s go back to the terminal and use the following code to install it:

yarn add axios

It seems like the most important plugins are installed, so we can take care of the CORS. To avoid it, we need to set the proxy in our package.json file. Just below the scripts, let’s add the following line of code, but remember to set the proxy for your backend URL. In my case, it’s http://localhost:4000.

"proxy": "http://localhost:4000",

Great! Now, let’s add the CDN for the CSS framework, which will be Bulma, and we will also need the icons.

3. Add Bulma and icons

Let’s go to bulma.io, and in the documentation, we can find the link to the CDN and Font Awesome icons, which we have to add.

Open the following file public\index.html, and in the head section of our main file, let’s add the following code.

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.0/css/bulma.min.css">
<script defer src="https://use.fontawesome.com/releases/v5.3.1/js/all.js"></script>

Now, we can start creating our application, so let’s open the code in your favorite code editor, and let’s begin!

4. Create a new component

Inside the src folder, let’s create the components folder, where we will be creating our components. Inside the newly created folder, let’s create the folder for our transactions component, and inside that folder, let’s create transactions.jsx file.

Inside this file, let’s import React, and let’s start creating our component.

import React, { useEffect, useState } from 'react';

function Transactions() {
  return (
    <div className="transactions section"> 
      <div className="card has-table has-mobile-sort-spaced">
        <header className="card-header">
          <p className="card-header-title">
            Transactions History
          </p>
        </header>
        <div className="card-content">
          <div className="table-wrapper has-mobile-cards">
            <table className="table is-striped is-hoverable">
              <thead>
                <tr>
                  <th>ID</th>
                  <th>Amount</th>
                  <th>Category</th>
                  <th>Date</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td>1</td>
                  <td>200$</td>
                  <td>shopping</td>
                  <td>10/04/2020</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  );
}

export default Transactions;

When we have created the code of our transactions component, let’s go to the App.js file, and let’s display the component.

import React from 'react';
import Transactions from './components/transactions/transactions';
import './App.css';

function App() {
  return (
    <div className="App has-background-light">
      <div className="container is-fluid">
        <div className="columns">
          <div className="column">
            <Transactions />
          </div>
        </div>
      </div>
    </div>
  );
}

export default App;

As the last step at this point, we will add some custom styles in our App.css file.

.App {
  height: auto;
  min-height: 100vh;
  width: 100vw;
  overflow: hidden;
}

.transactions .card-content {
  padding: 0;
}

.transactions table {
  width: 100%;
}

.transactions .table-wrapper {
  overflow: auto;
  max-height: 90vh;
}

.transactions .card .card-header {
  border-bottom: 1px solid rgba(24,28,33,.06);
}

.transactions .card {
  border-radius: 6px;
}

Great, now we can go and create our GraphQL query and prepare the axios call. 

5. Create GrpahQL API query

Let’s open the transactions.jsx file, and let’s start by importing the axios, defining our state transactions, and defining our query.

import React, { useEffect, useState } from 'react';
import axios from 'axios';

function Transactions() {
  const [transactions, setTransactions] = useState([]);
 
  const query = `{ 
    expenses {
      id,
      date,
      category,
      amount,
      type,
    }
  }`;

  ... 
}

When it’s ready, let’s use the useEffect() hook to build the API call.

useEffect(() => {
  axios({
    url: '/graphql',
    method: 'post',
    data: {
      query,
    }
  }).then((result) => {
    setTransactions(result.data.data.expenses);
  });
}, []);

Great, we have our data saved in the state, so now we can map it in our table. 

6. Map data

Let’s find the table row, which we are going to use to display the data, and let’s map our data to display it.

<tbody>
  {transactions.map((item) => (
    <tr key={item.id}>
      <td>{item.id}</td>
      <td><span className={`${item.type === 'incoming' ? 'tag is-success' : 'tag is-danger'}`}>{item.type === 'incoming' ? '' : '-'} {item.amount} $</span></td>
      <td>{item.category}</td>
      <td>{item.date}</td>
    </tr>  
  ))}  
</tbody>

Now you can see the table, and the last thing that I’d like to do here is to add a small icon to each category.

7. Set icons

To set the specific icon, I’m going to create the function with a switch statement where I’ll assign the particular icon to each category and then call it in the table cell.

const getIcon = (category) => {
    let icon;
    switch(category) {
      case 'entertainment':
        icon = 'birthday-cake';
        break;
      case 'food':
        icon = 'pizza-slice';
        break;
      case 'bills':
        icon = 'home';
        break;
      case 'clothes':
        icon = 'tshirt';
        break;
      case 'cosmetics':
        icon = 'bath';
        break;
      case 'health':
        icon = 'first-aid';
        break;
      case 'electronics':
        icon = 'tv';
        break;
      case 'commuting': 
        icon = 'car-side';
        break;
      case 'freelance':
        icon = 'laptop-code';
        break;
      case 'salary':
        icon = 'wallet';
        break;
      case 'passive':
        icon = 'money-check-alt';
        break;
      default:
        // code block
    }
    return icon;
  }

  ...

 <td><i className={`fas fa-${getIcon(item.category)}`}></i> {item.category}</td>

And that’s it! Let’s check the application right now. The result should look like the image below.

Conclusion

Congratulations!

In this tutorial, you’ve learned how to get data from GraphQL API in ReactJS using axios. Now you can use both APIs, REST, and GraphQL, and you are also able to figure out which one would be better for your application.

Don’t forget to check out our ExpressJS course, where you can learn how to build GraphQL API on backend.

If you missed some code, feel free to check it our here:

ReactJS Course: Lesson 1 - Code

Thank you for reading,
Anna from Duomly

Anna Danilec

If you liked it share and comment!