0
votes

I have a relay container that conditionally fetches some fields using @include(if: $variable), but I have to write the directive for each individual field:

const relayOptions = {
  initialVariables: {
    expandDetails: false,
  },
  fragments: {
    company: Relay.QL`
      fragment on Company {
        id
        name
        employees @include(if: $expandDetails) {
          fullName
        }
        admins @include(if: $expandDetails) {
          fullName
        }
        departments @include(if: $expandDetails) {
          name
        }
      }
    `,
  },
}

Is there any way that I could write the directive only once, for example something like this (and I know this code won't work):

const relayOptions = {
  initialVariables: {
    expandDetails: false,
  },
  fragments: {
    company: Relay.QL`
      fragment on Company {
        id
        name
        @include(if: $expandDetails) {
          employees {
            fullName
          }
          admins {
            fullName
          }
          departments {
            name
          }
        }
      }
    `,
  },
}

I tried some other crazy ways but none of them worked, I got this error:

'@include' can't be applied to fragment definitions (allowed: fields, fragment spreads, inline fragments)

Edit: Note: I need to do that to avoid fetching data unnecessarily. I'd like to only fetch the data if the collapsible component displaying the data is expanded (planning to do that using setVariables after component is mounted). In this example there are only 3 conditional fields, but in the actual case I'm trying to solve for there is a lot more than that.

1

1 Answers

3
votes

You can put the directive on an inline fragment, and just use the same type as the outer field:

fragment on Company {
  ... on Company @include(if: $expandDetails) {
    employees { fullName }
    admins { fullName }
    departments { fullName }
  }
}