Overview

Part of the GraphQL Series

In my previous GraphQL blog post, I promised to follow it up with an article about what an Apollo GraphQL client might look like.

In this post we do just that, still about Formula 1, (as an aside yesterday found out that Daniel Ricciardo will be moving to McLaren to replace Sainz who will be replacing Vettel at Ferrari).

Apollo Client to create modern web applications

Apollo Client is the perfect pairing for the F1 GraphQL Server we built in the last blog post. But before we start, we have to know a little bit more about it. And as I will explain further, there may be more to it than what its name might suggest.

What we built

In this article we will be inspecting an Apollo GraphQL Client that I built specially for the server we created for the last article. I am calling it F1 GraphQL Client, a reference ReactJS GraphQL consumer. Nothing fancy, rough around the edges, but it serves the purpose of showcasing how easy it is to get it up and running.

I Love Formula 1, pictured above is the new 2021 F1 car design.

All source code is available at FullstackDeveloper.Tips Github and forever free however you want to use it. It is also hosted at AWS S3, so go ahead play with it to your heart’s content. As usual, I have used Github Actions to automatically deploy it to S3 once it is pushed to the repo.

We are building a simple GraphQL consumer using Apollo Client

What is Apollo Client?

Apollo Client is a complete state management library for JavaScript apps. Simply write a GraphQL query, and Apollo Client will take care of requesting and caching your data, as well as updating your UI. - Apollo Client docs

What?!? Apollo Client is a state management library? That I did not expect. This is the very first statement that you will read in the official online Apollo Client documentation. I wasn’t really convinced at first, I thought, with ReactJS and all other supporting libraries, why would I need yet another one?

Please read on and find out.

Declarative configuration

Because GraphQL is still using HTTP, any of the usual libraries that we use in REST API can be used with GraphQL, eg, fetch, axios, superagent, or simply just XHR. We can use them, however, forget about them for the moment. Let’s try the Apollo Client and prepare to be blown away.

Using Apollo client and and the library’s useQuery hook, you can create your GraphQL requests declaratively, and not have to create data access code with your favorite library.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
export default function QualifyingResultsTable() {
  const classes = useStyles();
  const { filters } = useContext(AppState);
  const { loading, error, data } = useQuery(QUAL_RESULTS, {
    variables: { season: filters.season }
  });
  if (loading) return (
    <Grid item xs={4} className={classes.root}>
      <CircularProgress size={20} className={classes.spinner} ></CircularProgress>
    </Grid>
  );
  if (error) return <p>Error :(</p>;
  const quals = data.qualifying[filters.detail] ? data.qualifying[filters.detail].QualifyingResults : null;  

  return (
    <TableContainer component={Paper}>
      <Table className={classes.table} aria-label="simple table">
        {/*... removed for brevity ...*/}
        <TableBody>
          {
            quals &&
            quals.map((result, row_i) => {                        
            return (
              <TableRow key={row_i}>
                <TableCell align="left" component="th" scope="row">{result.position}</TableCell>
                <TableCell align="left">{result.number}</TableCell>
                <TableCell align="left">{result.Driver.givenName}</TableCell>
                <TableCell align="left">{result.Constructor.name}</TableCell>
                <TableCell align="left">{result.Q1}</TableCell>
                <TableCell align="left">{result.Q2}</TableCell>
                <TableCell align="left">{result.Q3}</TableCell>
              </TableRow>
            );
            })
          }
        </TableBody>
      </Table>
    </TableContainer>
  );
}

On line number 4, you get loading and error flags built-in to indicate those states, and data containing the requested data. In the example on line 22, you can see the view directly using it. Isn’t that awesome?

Client-side caching for free

Without any configuration, all your requests are cached on the browser. So if you use the same query in other parts of your SPA, you will get instant response from your local Apollo Client cache. If there are advanced cases that is not handled by the default behavior, you can customize them, but this is out of scope for this article.

Try the caching functionality now. The first time you load 2019 data, there is a bit of a delay as the request completes. But you go away to another season, say 2018, and come back to 2019, it will be instant as that data is already in the Apollo Client cache.

Throw away Redux and MobX, state management is built-in

In the code snippet above, where we have error and loading and data, if we were not using Apollo Client, we would handle these manually by creating reducers in Redux or stores in MobX. But because client side caching is built-in, we can leverage this and use it as our app state management. Here’s more information about this from the source.

Handy developer tools

Development productivity is important to ensure adoption. One cool feature is a Chrome DevTools extension that allows you (in your local dev environment) easily interact with your GraphQL client and server, including your local Apollo Client cache.

When working locally Apollo Client Developer Tools is really handy

Easy integration with your favorite JS framework

I have shown the integration in ReactJS above, however, many other platforms are supported too like Angular, Vue, Meteor, and Ember, to name a few.

Conclusion

Today’s article is a concise introduction to Apollo Client, and and the sample application demonstrates that creating a GraphQL client is simple specially if you use Apollo Client. With it’s declarative style, caching, developer tools and easy integration with your project, you can get started and be productive in no time.

Please try F1 GraphQL Client live here! Source code for F1 GraphQL Client is available here.

Production Build

My Picks

These picks are things that have had a positive impact to me in recent weeks:

Resources

2023

Back to top ↑

2022

Back to top ↑

2021

Back to top ↑

2020

DynamoDB and Single-Table Design

9 minute read

Follow along as I implement DynamoDB Single-Table Design - find out the tools and methods I use to make the process easier, and finally the light-bulb moment...

Back to top ↑

2019

Website Performance Series - Part 3

5 minute read

Speeding up your site is easy if you know what to focus on. Follow along as I explore the performance optimization maze, and find 3 awesome tips inside (plus...

Back to top ↑