Codementor Events

You will Love GraphQL in React if read this post

Published Jul 17, 2019Last updated Jan 12, 2020
You will Love GraphQL in React if read this post

What is GraphQL? đŸ€”

GraphQL is a query language for your API, and a server-side runtime for executing queries by using a type system you define for your data.

In simpler terms, graphQL is a syntax that describes how to ask for data. It was released by Facebook publicly in 2015, and since then many companies have adopted GraphQL in their stack.

From the official docs:

Once a GraphQL service is running (typically at a URL on a web service), it can be sent GraphQL queries to validate and execute. A received query is first checked to ensure it only refers to the types and fields defined, then runs the provided functions to produce a result.

You can build a server that can respond to graphQL queries in whatever language you want. The client-side application doesn’t care about this until it can send a graphQL query to the endpoint and get the desired data.

Why use GraphQL ? đŸ’ȘđŸŒ

Many consider GraphQL as a replacement for REST which is quite inaccurate.
REST (Representational State Transfer) is an API design architecture used on network-based software to transfer the data.

It has many limitations. It could require multiple round trips to fetch related resources. Another common problem is under-fetching ( not getting everything in one go), or over-fetching ( getting more than what is needed in one go.

As the application grows, the number of endpoints that are required can also increase, and make the codebase maintenance much harder. The server decides what data is to be sent to the client, and the client has no control over it.

GraphQL provides a query language, specification, and collection of tools which helps solve these problems, with better performance and flexibility.

The biggest advantages are:

There would only be one endpoint ( most of the time ) which makes life easier
Client gets to decide what data to query

Let’s consider an example to make this more clear. Assume that you are building an app that shows details of Books. The book has the following fields — id, title, author, genre.

On one page, you want to display the id and title. On another page, you want to display the title and the author, and in a third page you want to display title and genre.

If you are to implement this optimally using a REST API architecture, you would need three different endpoints. By using graphQL , you can use a single endpoint that provides all the data, and query only the required data in from the client side application.

A GraphQL service is created by defining types and fields on those types, then providing functions for each field on each type. This makes graphQL less error prone.

GraphQL in React đŸ’»

Let’s dig into the topic of the post, which is getting started with graphQL in React. Although we went through a basic introduction of graphQL, this tutorial assumes that you are already familiar with React and implementing a simple React app. Now we will take a look at how to use graphQL in react.

React has a very active ecosystem surrounding it, and already have many tools that make using GraphQL a breeze.

Let ushave a look at all the packages required to get us started.

apollo-boost — It is a zero configuration way of getting started with GraphQL in react.
react-apollo — Apollo client is the best way to use GraphQL in client-side applications. React-apollo provides an integration between GraphQL and Apollo client
graphql-tag — A JavaScript template literal tag that parses GraphQL queries

and of course GraphQL.

Let us look at the actual code implementation.

First step is to import apollo-client from apollo-boost.

import ApolloClient from ‘apollo-boost’
import { ApolloProvider } from ‘react-apollo’

Once we have the apollo object, we will create an instance of apollo client with the uri property. This is the actual endpoint that will provide us with the data which will be displayed on our client side react application. This can be done using the following line of code.

const client = new ApolloClient({
    uri: ‘https://r95kv5p84n.lp.gql.zone/graphql',
})

For demo purposes, we have set up an endpoint that will provide us with book data — id, name, and author. Apollo launchpad helps you set up pseudo graphQL endpoints, which is really easy for demonstration purposes. As we mentioned earlier, the client side app doesn’t care how the server is built as long as the server accepts queries and return data.

Feel free to play around with it and make your own endpoints.

Next step is to connect Apollo and React. For this, we can use ApolloProvider from react-apollo. We should wrap the entire component with ApolloProvider as shown below.

import React from 'react'
import ApolloClient from 'apollo-boost'
import { ApolloProvider } from 'react-apollo'
import Books from './Books'

const client = new ApolloClient({
  uri: 'https://r95kv5p84n.lp.gql.zone/graphql',
})

const App = () => (
  <ApolloProvider client={client}>
    <nav className="navbar">
      <a className="navbar-brand" href="">
        GraphQL in React - Demo application
      </a>
    </nav>
    <div className="container">
      <Books />
    </div>
  </ApolloProvider>
)

export default App

Now let’s build the actual app. Since its a demo app, we will keep it simple and silly. Get the data and display it. Let us create a component called Books to display all the books.

import React from 'react'
import { Query } from 'react-apollo'
import gql from 'graphql-tag'

import Book from './Book'

const Books = () => (
  <Query
    query={gql`
      {
        allBooks {
          id
          title
          author
        }
      }
    `}
  >
    {({ loading, error, data }) => {
      if (loading) return <p>Good things take time....</p>
      if (error) return <p>Something went wrong...</p>

      return <div className="row">{data.allBooks.map(book => <Book book={book} />)}</div>
    }}
  </Query>
)

export default Books

We start by importing the required packages. We need gql to execute the actual query. To access the data, we wrap the actual component in a Query component with the required gql query passed in as query attribute.

Query component is used to execute a query from the backend. This will return the data with three params.

loading — to show the data is still loading
error — to indicate that some error was caused
data — the actual data as an array ( or as specified in the backend )

We can use a map function over data object and just display it in the browser.

As mentioned earlier, The cool thing about constructing the query on your client-side app is that you can control the fields you need. For example, if you only need the name of the book the query can be:

query={gql`
  {
    allBooks {
      id
      title
    }
  }
`}

This provides great flexibility in case of end-points with a large number of fields. You only need to implement a single endpoint, and based on the view construct the query and get the required data.

Now, we have successfully fetched data from a graphQL server and displayed data in a react client-side app.

If you like what you have read, follow me on this.
Best regards

Discover and read more posts from Teodor Malinas
get started
post commentsBe the first to share your opinion
Mark Cowell
5 years ago

Well written and I just loved it! Just from your writing I can say you are full expert at these things.
https://bestwashingmachine.in

Jose Antonio C
5 years ago

https://r95kv5p84n.lp.gql.zone/graphql

502 Bad Gateway: Registered endpoints failed to handle the request. If you’re the owner of this app, see this article for more information: http://bit.ly/2w0yJ4P

KV M
5 years ago

If you only need name of the book yhe query can be allBooks{ name}

Liked your article. It’s simple and clear to convey the idea of Graphql on react.

Teodor Malinas
5 years ago

If you want to learn how to implement query service instead of restful API in the node.js, I can detail about that as well.
Thank you for your like :)

KV M
5 years ago

First line was a correction to a code snippet in your post. Thought you might want to correct it.

Show more replies