4
votes

While defining fragments of a Relay container, we can conditionally include or skip fields. For example, the following code includes comments only if showComments variable is true.

Relay.createContainer(Story, {
  initialVariables: {
    numCommentsToShow: 10,
    showComments: false,
  },
  fragments: {
    story: (variables) => Relay.QL`
      fragment on Story {
        comments(first: $numCommentsToShow) @include(if: $showComments) {
          edges {
            node {
              author { name },
              id,
              text,
            },
          },
        },
      }
    `,
  }
});

How can we conditionally include fields in a mutation's fat query?

An use-use: Instead of having separate muttaions to update each field of a type, we could reuse the same mutation to update any field and fetch only that field in response. Doing so enables us to reduce payload.

This question is motivated by another question Reusing a Mutation in Relay.

1

1 Answers

0
votes

You can actually use string interpolation on the FatQuery:

getFatQuery() {
  return Relay.QL`
    fragment on EditCommentPayload {
      comment {
        ${this.props.fields.join(',')}
      }
    }
  `;

It seems a bit anti-GraphQL but unfortunately there are no variables for the fat query (related issue).