Part 6 - Fragments

This is part 6 of series

This part is based on the Fragments section of this tutorial

useFragment

After all the work we have done so far, following Fragments section in Relay tutorial is a breeze.

Commit: https://github.com/tuan/newsfeed-demo-app/commit/b3ce37e71a9007a9cd717ebd06d6cc5efa78ee64

There are a few things related to fragment that might be beneficial if you’re new to Relay:

  • Think of the Relay query as a tree: each fragment is a node. This Relay tree is a mirror of React component tree. With this in mind, when you re-use your component in an existing part of the component tree, you should also re-use, i.e. spread, your component’s fragment in the corresponding part of the Relay tree.
  • Use the following naming convention when naming your fragment: ComponentNameFragment_componentPropName. Here’s an example in Image.tsx:
    const ImageFragment = graphql`
      fragment ImageFragment_image on Image {
        url
      }
    `;
    
  • The type of your fragment key always has the suffix $key
  • Your fragment key is the nearest parent node in the Relay query where you spread your fragment

After making the changes, you should now see the timestamp rendered correctly

Fragment arguments

To follow along with the official Newsfeed tutorial, you need to update your servide to allow url field in Image type to take width and height parameters.

Based on previous decision made in Refactoring resolvers, we should convert fields in Image type to methods. This does not only make it consistent with other types, but also make it easy to support width and height parameters.

Commit diff: https://github.com/tuan/newsfeed-demo-app/commit/4190c1f7937c1eeb292cc63ebb2e2ffa8aa5f4a4

After making the change, you can test it out quickly using GraphiQL