Learn Relay/
← 0507 →

06 - mutation updater

Learn how to use updater to update your Relay Store without using a refetch query after a mutation.

Exercise

  • add an updater to the PostCommentCreate mutation (comment/PostCommentCreateMutation.tsx) to update the Relay Store properly: the new comment edge should be added to the PostComments_comments connection of the post

Write a comment in the first post and send it: it should show up in the comment list without a refetch.

Extras

  • use an optimisticUpdater to provide a fast feedback to the user
  • show the comments count and update it (the mutation already returns post { commentsCount })

Code Helpers

  • Get a record from the Relay store using a global id
const recordProxy = store.get(globalId);
  • Get the root field of the mutation payload
const newEdge = store.getRootField('PostCommentCreate').getLinkedRecord('commentEdge');
  • Query Type root id
import { ROOT_ID } from 'relay-runtime';
  • Get connection from name
const connection = ConnectionHandler.getConnection(parentProxy, connectionName);
  • Insert new edge to connection
ConnectionHandler.insertEdgeBefore(connection, edge);
ConnectionHandler.insertEdgeAfter(connection, edge);
  • Create new node in Relay store
const node = store.create(id, typename);
  • Set value of a node/record proxy
node.setValue(value, propertyName);
  • Set value that is an object or another record proxy of a node/record proxy
node.setLinkedRecord(recordProxy, propertyName);
Next: useRefetchableFragment →
Loading editor…
localhost:7500 · in-browser GraphQL server
Checks verify your solution against the running app.
  • ○Sending a comment runs PostCommentCreateMutation
  • ○The new comment shows up without a refetch query
  • ○The comment edge is added to the end of the PostComments_comments connection
  • ○(extra) Optimistic updater shows the comment before the server answers