DEV Community

Cover image for Learn GraphQL and Apollo Client With a Simple React Project
Nitin Sharma
Nitin Sharma

Posted on • Originally published at blog.locofy.ai

Learn GraphQL and Apollo Client With a Simple React Project

There were only static files in the early days of web development but since then, a lot has changed. Today’s online applications are powered by a variety of technologies, including databases, web sockets, real-time data, authentication, and many more.

It is a common practice these days to decouple the front end from the backend & have separate teams working on each. This makes it essential to create an interface so they can communicate with each other smoothly.

Application Programming Interface(API) is an industry-standard way of connecting the two.

Considering how APIs work, we can say that the client sends a request, the server processes the request, and then sends the response.

For example, let’s ask the server for a variety of books. You can imagine the client as a web browser, such as Google Chrome, and the server as the data repository that sends back a lot of data present in it(or in external databases).

We can receive something like this:

Img

However, the client’s ability to act depends on the data it can receive from the API & besides that, it may not need all the data that is sent from the API server.

In an ideal scenario, the front end should be able to communicate with the backend and get exactly the data it needs. That’s where GraphQL comes in.

GraphQL: A Modern Way to Build APIs

GraphQL is essentially a query language. It provides freedom by enabling you to perform a number of things, such as setting up your API, running queries, modifying the data, and more.

In short, it gives the client(front-end) the exact properties it needs.

Let’s take an example to understand GraphQL. We’ll fetch data using REST and GraphQL to highlight their differences.

Assume we make the following request:

GET https://rickandmortyapi.com/api/character
Enter fullscreen mode Exit fullscreen mode

The response will be as follows:

{
  "info": {
    "count": 826,
    "pages": 42,
    "next": "https://rickandmortyapi.com/api/character?page=2",
    "prev": null
  },
  "results": [
    {
      "id": 1,
      "name": "Rick Sanchez",
      "status": "Alive",
      "species": "Human",
      "type": "",
      "gender": "Male",
      "origin": {
        "name": "Earth (C-137)",
        "url": "https://rickandmortyapi.com/api/location/1"
      },
      "location": {
        "name": "Citadel of Ricks",
        "url": "https://rickandmortyapi.com/api/location/3"
      },
      "image": "https://rickandmortyapi.com/api/character/avatar/1.jpeg",
      "episode": [
        "https://rickandmortyapi.com/api/episode/1",
        "https://rickandmortyapi.com/api/episode/2",
        // ...
      ],
      "url": "https://rickandmortyapi.com/api/character/1",
      "created": "2017-11-04T18:48:46.250Z"
    },
   // ...
 ]
}
Enter fullscreen mode Exit fullscreen mode

Here, we have a considerable amount of data with a lot of properties in the “/character” API endpoint, but what if we just need a few of them? In this situation, GraphQL can be useful.

Let’s implement a GraphQL example now.

Query/ Input:

query {
  characters{
    info{
      count
    },
    results{
      id,
      name,
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Response/ Output:

{
  "data": {
    "characters": {
      "info": {
        "count": 826
      },
      "results": [
        {
          "id": "1",
          "name": "Rick Sanchez"
        },
        {
          "id": "2",
          "name": "Morty Smith"
        },
        {
          "id": "3",
          "name": "Summer Smith"
        },
        {
          "id": "4",
          "name": "Beth Smith"
        },
        …
      ]
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

You can see that we requested some specific properties like “count”, “id”, and “name”, which are now part of the output.

In other words, we define the specific parameters inside the query object and then get the response depending on those. This is how GraphQL differs from a standard REST API.

Rise of GraphQL in Recent Years

GraphQL being a query language enables flexible communication between clients and servers by defining queries and even mutating the data.

It was created by Facebook in 2012 for internal usage. Later, It became accessible to the public, in 2015. And that’s where it started to compete with RESTful APIs.

As time went on, it was used all around the world. People even predicted that GraphQL will replace REST.

Even the State of JavaScript study found that from 2017 to 2020, GraphQL was one of the top technologies developers were interested in.

Img

As you can see in the image below, only 6% of developers were adopting GraphQL technology in 2016; by 2020, that number had risen to 47%.

Stats

So it is apparent from the surveys that GraphQL is here to stay and will be widely used.

Fetching GraphQL Data from React using Apollo Client

GraphQL_Img

We are all familiar that a client and server are necessary when developing a website.

In this blog, we will use React on the frontend side and a GraphQL server on the server side.

We will use this particular GraphQL serverto fetch the data in React. You can read more about it here.

Now let’s create a react app.

1. Create a React App

npx create-react-app graphql-tut
Enter fullscreen mode Exit fullscreen mode

You need to install two npm packages i.e. GraphQL and Apollo Client.

To install GraphQL and Apollo Client, execute the following command:

npm install @apollo/client graphql
Enter fullscreen mode Exit fullscreen mode

React doesn’t have support for GraphQL by default, hence it cannot connect to a GraphQL server and run queries against it. There’s where Apollo Client comes in handy. Apollo Client is a leading state management library that combines React with GraphQL, two incredibly helpful tools for creating websites and apps.

After installing the packages, you would have a GraphQL server, a React app, and the necessary npm dependencies installed. Now you can use the Apollo Client to connect the React app to GraphQL.

Before proceeding further, delete the file's logo.svg, setupTests.js, reportWebVitals.js, and App.test.js files from the src folder; we don’t need any of these.

We can start with the index.js file.

2. Modifying index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import { ApolloClient, ApolloProvider, InMemoryCache } from '@apollo/client'

const client = new ApolloClient({
  uri: "https://rickandmortyapi.com/graphql",
  cache: new InMemoryCache(),
})

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <ApolloProvider client={client}>
    <App />
  </ApolloProvider>
);
Enter fullscreen mode Exit fullscreen mode

Here, we created a client and passed a few arguments.

For the uri property, we have our GraphQL server link and our GraphQL query results are saved by Apollo Client in a local InMemoryCache. As a result, Apollo Client can respond to requests for already-cached data instantaneously, without performing the same requests again.

Lastly, we use ApolloProvider to wrap the app component.

Now let’s query & render data.

3. Rendering a list of data inside App.js

So far, we have connected our app with GraphQL and now it’s time to render a list of data.

For that, inside the App.js file, we have to import useQuery and gql from Apollo Client.

import { useQuery, gql } from "@apollo/client"
Enter fullscreen mode Exit fullscreen mode

Now it’s time to query the specific properties that we need inside our app.

const GET_LIST = gql`
query {
    characters{
        results{
            id,
            name,
        }
    }
}
`
Enter fullscreen mode Exit fullscreen mode

Here, we have used gql template literal to query the id and name property present in the character object(in the GraphQL server).

Now let’s render the list of data inside the App component.

function App() {
    const { data, loading, error } = useQuery(GET_LISTS);
    if (loading) return 'Loading...';
    if (error) return `Error! ${error.message}`;
    return (
    <div>
    {
      data.characters.results.map(item => {
        return(
            <div key={item.id} style={{display: 'flex', flexDirection: 'row'}}>
                <h2>{item.id}.  </h2>
                <h2>{item.name}</h2>
            </div>    
        )
      })  
    }
    </div>
    )
}
Enter fullscreen mode Exit fullscreen mode

Here, we used a useQuery hook before destructuring and rendering the data.

Now it’s time to run the react app:

npm start
Enter fullscreen mode Exit fullscreen mode

The result appears as follows:

Rick Sanchez

Morty Smith

Summer Smith

Beth Smith

Jerry Smith

Abadango Cluster Princess

Abradolf Lincler

Adjudicator Rick

Agency Director

Alan Rails

Albert Einstein

Alexander

Alien Googah

Alien Morty

Alien Rick

Amish Cyborg

Annie

Antenna Morty

Antenna Rick

Ants in my Eyes Johnson
Enter fullscreen mode Exit fullscreen mode

You may experiment more with GraphQL by changing the queries.

It is also possible to combine GraphQL with other well-known frameworks like Vue and Angular. Even Apollo Client and GraphQL are compatible with React Native.

Should Every API Use GraphQL?

GraphQL has emerged as an alternative to REST since its launch. The ability of GraphQL to request specific data via queries and have a single endpoint makes us wonder whether every API should utilize GraphQL. This has provided developers with more options & sparked debates on which one is better.

The short answer is, it depends upon the data and how it is structured.

GraphQL may be used to retrieve specific data while avoiding numerous requests and saving bandwidth and time. In contrast, there may be instances when you need to make multiple requests, manage file uploads, and enable HTTP status codes, in that case, REST might be handy.

As a result, it is dependent on how you want to obtain the data and which features you want to employ. It also comes down to whether the particular framework or software you are using even allows GraphQL or not.

You would need to build the app with components that can accept props(data from these APIs) and render them. For this, you can use the Locofy.ai plugin to rapidly generate frontend code that accepts props to test & see these GraphQL APIs in action in pixel-perfect UIs.

Create a Full Stack App using Locofy and GraphQL

The Locofy.ai plugin for Figma & Adobe XD enables you to take your designs to high-quality, production-ready frontend code in a matter of few hours, which would have otherwise taken you days. You can make the code highly extendible inside the Locofy Builder where you can break down your designs into components as well as set props for each of these components & finally export the code.

You can pick a framework of your choice from the likes of React, Next.js, Gatsby, React Native, or even HTML-CSS.

This will generate code that you can easily extend and pass data from your API. We covered how to do this by building a full stack app with GraphQL and React, with help of tools like Locofy.ai and Hasura at a developer event in San Francisco in September 2022, and documented it in our recent guide.

Locofy.ai enables you to ship 5x faster by providing you with a polished codebase that you can easily extend with these APIs.

Hope you like it.

That’s it — thanks.

Top comments (0)