• A Front End Developer’s Guide to GraphQL
  • PEGGY RAYZIS
  • The Nuggets translation Project
  • Permanent link to this article: github.com/xitu/gold-m…
  • Translator: ellcyyang
  • Proofreader: Xekin-fe, Xueshuai

No matter how complex or simple your application is, you will always get data from a remote server. On the front end, this means making REST connections to an endpoint, transforming and caching server replies, and rerendering the UI. REST has been the standard API for many years, but in the past year a new API technology called GraphQL has become popular with its great development experience and narrative data fetching approach.

In this article we’ll walk through a series of examples of how GraphQL can help you get around the pain point of fetching remote data. If you’re new to GraphQL, fear not! I’ll list some learning resources to help you learn GraphQL using the Apollo stack, and you’ll be one step ahead of everyone else.

GraphQL 101

Before we can figure out why GraphQL makes life easier for front-end engineers, we need to figure out what it is. When we talk about GraphQL, we are referring either to the language itself, or to the entire rich tool ecosystem associated with it. At its core, GraphQL is a typed query language developed by Facebook that allows you to express your data needs in a narrative manner. The format of your query results should match your query statements. In the following example, we expect an object with the properties currency and rates, which in turn are an array of objects containing the currency and rate keywords.

{
  rates(currency: "USD") {
    currency
    rates {
      currency
      rate
    }
  }
}
Copy the code

When we talk about GraphQL in the broad sense, we are referring primarily to the ecosystem of tools that help deploy GraphQL into applications. On the back end, you’ll use the Apollo server to create a GraphQL server — an endpoint that parses GraphQL requests and returns data. How does the server know which data to return? You need to use the GraphQL tool to create a dictionary (your data blueprint) and a decomposition map (a set of functions for retrieving data from a REST endpoint, database, or whatever).

But it’s actually simpler than it sounds — with the Apollo launcher (a GraphQL server console), you can create a working GraphQL server in a browser with no more than 60 lines of code! 😮 We refer to the launcher I created, which contains the Coinbase API mentioned in the article.

You’ll connect to your own GraphQL server and application using the Apollo client, a flexible and fast client that retrieves, caches, and updates data for you. Since the Apollo client is not coupled to the visual layer, you can write it in React, Angular, Vue, or even native JavaScript. In addition to being cross-framework, Apollo is also cross-platform, with React Native and Ionic support.

Give it a try! 🚀

Now that you know what GraphQL is, try out a few examples of how to apply Apollo to your front-end work. I’m sure you’ll eventually agree that a GraphQL-based architecture using Apollo will help you transfer data faster.

1. Add new data requirements without adding new endpoints

We’ve all been there: you spend a few hours creating a perfect UI component, and then suddenly the product requirements change. You suddenly realize that in order to get the data you need to implement your new requirements, you will have to implement a complex waterfall model that receives API requests — or worse — a new REST endpoint. Then your work gets blocked and you have to ask the back end to add a new endpoint for this component.

This common problem is no longer present in GraphQL because the data you need on the client side is no longer coupled to an endpoint’s resources. Instead, your request to the GraphQL server always connects to the same endpoint. Your server specifies all available resources through the dictionary you send, and lets your query define the format of the results you get. Let’s illustrate these concepts with the previous example on my startup console:

In lines 22 to 26 of our dictionary, we define the ExchangeRate type. These fields list all the resources that can be queried in our application.

type ExchangeRate {
  currency: String
  rate: String
  name: String
}
Copy the code

In REST, we are limited by what data sources can provide. If your /exchange-rates endpoint does not contain name, you must connect to a new endpoint such as /currency to get the data or create it if the data does not exist.

With GraphQL, we can check the dictionary to see that the Name field is queryable. Try adding the Name field to the right panel of the boot pad, and then run.

{
  rates(currency: "USD") {
    currency
    rates {
      currency
      rate
      name
    }
  }
}
Copy the code

Now, delete the name field and re-execute the query. See the format change in your query results?

Your GraphQL server will always faithfully return the data you ask for, not more. This is very different from REST — where you have to filter and transform the data into what your UI components need. Not only does this save time, but it also reduces the network load and CPU storage required to load and parse the data.

2. Compress your state management template

Generally speaking, retrieving data involves updating your application’s state. You usually need to write code to track at least three behaviors: when the data was loaded, whether the data arrived successfully, and whether the data failed. Once the data arrives, you must transform it into what your UI components expect, standardize it, cache it, and update the page. The process is repetitive, requiring countless lines of template code to handle a single request.

Let’s take a look at how the React sandbox Apollo client eliminates this boring process in this example. Look at list.js and drag the scroll bar to the bottom.

export default graphql(ExchangeRateQuery, {
  props: ({ data }) => {
    if (data.loading) {
      return { loading: data.loading };
    }
    if (data.error) {
      return { error: data.error };
    }
    return {
      loading: false,
      rates: data.rates.rates
    };
  }
})(ExchangeRateList);
Copy the code

In this example, React Apollo, the React integration for the Apollo client, associates our exchange rate query with the Exchange Server component. Once the Apollo client processes that query, it automatically tracks the load and error status and puts it into data Prop. When the Apollo client receives the results, it updates the Data Prop based on the query results and then updates the UI with the exchange rates needed in the rendering.

The Apollo client does the data formatting and caching for you underneath. Try clicking on different currencies in the right pane to see the data refresh. Now, pick a currency again, and see how the data immediately appears? This is Apollo cache work. You can get these for free from the Apollo client with no extra setup. 😍 Open index.js to see our code for initializing the Apollo client.

3. Quick debugging using Apollo DevTools and GraphiQL

Looks like the Apollo client has done a lot of work for you! How do we take a peek inside to see how it works? With full visibility of stored checks and queries and transitions, Apollo DevTools not only answers these questions, but also makes debugging boring and even fun! 🎉 This is available in a plugin for Chrome and Firefox, and will soon be available for React Native as well.

If you want to try it out, follow the previous example, install Apollo DevTools on your favorite browser and navigate to our CodeSandbox. You will need to click “Download” in the top navigation bar, unpack the file, run NPM install and then NPM start to run the example locally. Once you open your browser’s development tools panel, you should see a TAB called Apollo.

First, let’s examine the storage inspector. This TAB reflects the status in the Apollo Client cache, making it easier to determine if your data is correctly stored in the Client.

Apollo DevTools lets you also test your queries and changes in GraphiQL, an interactive query editor and document browser. In fact, we already used GraphiQL when we tried to add fields in the first example. For review purposes, GraphiQL completes automatically when you enter queries into the editor and automatically generates documents based on the GraphQL type system. This is extremely useful for extending the dictionary and incurs no maintenance costs to the developer.

Try executing a query in GraphiQL in the right panel of my boot console! Hover over the query editor field and click the prompt box to open the document browser. If your query runs successfully in GraphiQL, you can be 100% sure that the query will also run successfully in your application.

Upgrade your GraphQL skills

Good for you! You can see here! 👏 hopes you enjoyed the examples and are starting to understand how GraphQL should be used on the front end.

Want to learn more? 🌮 Add “Keep learning GraphQL” to your 2018 New Year’s resolutions! Because I hope it will be more popular in the New Year. Here’s an example of how to use a newly learned concept:

  • React: codesandbox. IO/s/jvlrl98xw…
  • Presents (Ionic) : github.com/aaronksaund…
  • Vue: codesandbox. IO/s / 3 vm8vq6kw…

Stick with GraphQL (remember to follow us on Twitter @apollographQL)! 🚀


The Nuggets Translation Project is a community that translates quality Internet technical articles from English sharing articles on nuggets. The content covers Android, iOS, front-end, back-end, blockchain, products, design, artificial intelligence and other fields. If you want to see more high-quality translation, please continue to pay attention to the Translation plan of Digging Gold, the official Weibo, Zhihu column.