Learn Relay/
← 1315 →

14 - Optimistic updates (bonus)

Mutations are a round trip to the server. With a slow network the user clicks "like" and nothing happens for a while. Relay can apply an optimistic update to the store right away, and replace it with the real server response when it arrives.

Set the latency in the Network tab to 2000ms and click the like button to feel the problem.

Exercise

  • Add an optimisticResponse to the like/unlike mutations in Post.tsx, so the likes count and the heart change instantly
  • Add an optimisticUpdater to the PostCommentCreate mutation that
    • increments commentsCount of the post
    • creates a new Comment record (store.create) and inserts an edge in the Post_comments connection (ConnectionHandler.createEdge + ConnectionHandler.insertEdgeAfter)

The checks also verify that an optimistic update is rolled back when the server does not confirm it.

Extras

  • use an optimisticResponse + @appendEdge for the comment instead of an optimisticUpdater
  • watch the Relay Store tab while a mutation is in flight
  • show the comment in a lighter color while it is still optimistic (hint: the id starts with client:)
Next: Fetch policies & refreshing →
Loading editor…
localhost:7500 · in-browser GraphQL server
Checks verify your solution against the running app.
  • ○Posts are rendered
  • ○Like updates the UI before the server responds (optimisticResponse)
  • ○Unlike updates the UI before the server responds
  • ○A new comment shows up before the server responds (optimisticUpdater)
  • ○The optimistic update is rolled back when the server does not confirm it