Learn Relay/
← 1214 →

13 - Declarative directives

Learn how to use declarative directives to modify GraphQL data and see the connection updating automatically, without the need to refetch or write an updater function.

Exercise

  • put your user token in the Authorization header on the Network Layer (relay/fetchGraphQL.tsx, getToken() from relay/getToken.tsx already returns your token, this replaces pnpm get-token)
  • create a PostCreateMutation in PostCreateMutation.tsx using @appendEdge or @prependEdge (try both to see the difference)
  • commit the mutation in Feed.tsx when clicking Post, passing the Feed_posts connection id in $connections

Extras

  • add a PostDeleteMutation using @deleteEdge and use it in the delete button of Post.tsx (you can only delete your own posts)

Code Helpers

PostCreateMutation

mutation PostCreateMutation($input: PostCreateInput!, $connections: [ID!]!) {
  PostCreate(input: $input) {
    success
    error
    postEdge @appendEdge(connections: $connections) {
      node {
        id
        content
        author {
          name
        }
      }
    }
  }
}

Getting the connection id

// select __id in the connection (see Feed_query)
const connectionID = posts.__id;
// OR
const connectionID = ConnectionHandler.getConnectionID(ROOT_ID, 'Feed_posts');
Your user token

The replacement for pnpm get-token. It logs you in as Sibelius Seraphini.

JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6InUxIn0.relay-workshop
Next: Optimistic updates →
Loading editor…
localhost:7500 · in-browser GraphQL server
Checks verify your solution against the running app.
  • ○PostCreateMutation uses @prependEdge or @appendEdge(connections: $connections)
  • ○The network layer sends the Authorization header
  • ○Clicking "Post" sends PostCreateMutation with the connections
  • ○The new post shows up in the feed without a refetch