June 02, 2017

Relay Modern’s @connection directive

The @connection directive is new to Relay Modern and unfortunately doesn’t have any official documentation. In this article, we want to give a brief overview on how to use it.

Relay Modern

If you tried to get started with Relay Modern yourself, chances are you came across the updated Todo Example project on GitHub. If you’ve also studied the mutations in that project, you might have noticed the @connection directive that you need to specify when querying lists of items.

This directive is new to Relay Modern and unfortunately doesn’t have any official documentation yet. In this article, we want to give a brief overview on how to use it.

In Relay, lists are represented through the concept of connections. This facilitates the implementation of a cursor-based pagination approach on the client.

The @connection directive takes two arguments:

  • key: specifies how Relay will refer to this connection in its internal cache
  • filter: represents an array of constraints that are used to filter the items in the connection

Let’s take a look at how the directive is used in the Todo example:

TodoList.js

In TodoList.js, the data dependencies for the TodoList component are declared in the form of a GraphQL fragment. todos refers to a connection that's defined in the GraphQL schema. When requesting the items from this list, the @connection directive is used alongside the todos field. Relay will use the specified key TodoList_todos in its internal cache to refer to that connection.

AddTodoMutation.js

The key is used again in AddTodoMutation.js. This time, its purpose is to pull the connection from the internal cache using the ConnectionHandler API. The key is passed to the call to ConnectionHandler.getConnection(...). This allows to retrieve the list from the cache and update it manually with the new todo item that was created through the mutation.

Don’t miss the next post!

Sign up for the Prisma Newsletter