GraphQL and Apollo Client by Example: Part 4

June 04, 2018 0 Comments

GraphQL and Apollo Client by Example: Part 4



Exploring arrays of complex types.

This article is part of a series starting with GraphQL and Apollo Client by Example: Part 1.

Array of Complex Types

In the previous example, the local state consisted of a singular primitive type (an integer counter). We now add some complexity by adding an array of complex types; an array of Todos. This example is heavily inspired by the todo example provided in the apollo-link-state repository.

The defaults.js and typeDefs.js files are fairly obvious.



The resolvers.js requires some explanation:



  • The addTodo mutation is fairly straightforward; except it is required to supply a typename property on the newTodo; it is a property used internally by Apollo Client to create the keys (for looking up todos) of the form typename:id.
  • The toggleTodo mutation is a bit more mysterious (the whole readFragment thing) until you understand how Apollo Client automatically normalizes array data under the hood (demonstrated next).

Say we add three todos using the Apollo Client Developer Tools:

and inspect the cache:


  • Again, there is a bug where you have to mutate the state from the web application (after mutating in the tool) to trigger rendering updates in both the web application and in the tool itself.
  • As you can see here, Apollo Client has stored the todos by their lookup key (e.g., TodoItem:0). The todos array is then simply an array of these lookup keys.
  • With this in mind, readFragment allows you to return a singular todo by the lookup key. Likewise writing { id, data }, updates a singular todo.

Using Complex Types in React

The final implementation is an application that allows you (in addition to the counter feature from before) to add todos, see the list of todos, and clicking on a todo toggles if it is complete or not.

The solution consists of the the following components:

The one new concept is that in Todo.jsx, we see that you can supply pre-defined parameters to the query (in this case a mutation).


Next Steps

We hit some random topics in GraphQL and Apollo Client by Example: Part 5 before moving onto interacting with servers.

Tag cloud