Learn Relay/
← 0709 →

08 - useSubscription

Learn how to use useSubscription to listen for changes in your GraphQL server.

Exercise

  • add the PostNewSubscription subscription in postSubscription/PostNewSubscription.tsx
  • complete the useNewPostSubscription hook to subscribe to new Posts calling useSubscription
  • show a snackbar (toast) with the new post author using enqueueSnackbar from useSnackbar
  • add an updater to add the new post to the top of the feed (Feed_posts connection), avoiding duplicated posts

Use the + simulate new post button (above the preview) to make another user create a post.

Extras

  • add "See" and "Dismiss" actions to the snackbar
  • do not show the snackbar when the new post was created by me

Code Helpers

  • PostNewSubscription
subscription PostNewSubscription($input: PostNewInput!) {
  PostNew(input: $input) {
    post {
      id
      content
      author {
        id
        name
      }
      meHasLiked
      likesCount
      ...Post_post
      ...PostComments_post
    }
  }
}
  • using @workshop/relay connectionUpdater helper to add an edge to a connection
connectionUpdater({
  store,
  parentId: ROOT_ID,
  connectionName: 'Feed_posts',
  edge: postEdge,
  before: true,
});
Next: usePreloadedQuery →
Loading editor…
localhost:7500 · in-browser GraphQL server
Checks verify your solution against the running app.
  • ○PostNewSubscription.tsx declares the PostNewSubscription subscription
  • ○The app subscribes to PostNewSubscription
  • ○A toast is shown when someone creates a new post
  • ○The new post is added to the top of the feed