Learn Relay/
← 16

17 - @required & error boundaries (bonus)

In GraphQL most fields are nullable: Post.author is User (not User!) because the author may have deleted their account, and Post.content may be null too. Instead of sprinkling ?. and ifs everywhere, Relay lets you declare what should happen when a field is null with the @required directive.

Exercise

  • A post without an author should simply not be rendered: add @required(action: LOG) to author and return null from Post when the fragment data is null
  • @required(action: LOG) reports to the Environment: add a relayFieldLogger to relay/Environment.tsx that console.warns the missing_required_field.log events (open the Console tab)
  • A post without content is a bug: add @required(action: THROW) to content. The error is caught by FeedErrorBoundary, and its retry button fetches the query again

The checks change the server data (they "delete" an author and a content) and click Reload. Today a post without author crashes the whole feed with Cannot read properties of null.

Extras

  • try @required(action: NONE) on author { name } - what happens to post.author?
  • move the error boundary around each Post, so a broken post does not hide the whole feed
Loading editor…
localhost:7500 · in-browser GraphQL server
Checks verify your solution against the running app.
  • ○Renders the 5 posts
  • ○A post without author is not rendered, and the rest of the feed still works (@required LOG)
  • ○A post without content throws and the error boundary shows the error (@required THROW)
  • ○retry fetches the posts again and recovers