Support for relay connection types

When you define a field as a union of two types (for example, machines have Ships and Droid), then in Relay you can do something like this:

fragment on Faction@ relay(plural: true) {
  name,
  machines {
    ... on Ship {
      name
    }
    ... on Droid {
      name,
      primaryFunction
    }
  }
}

therefore, under the machines, maintain your objects correctly, but if you want to do this using fragments from external components:

fragment on Faction@ relay(plural: true) {
  name,
  machines {
    ${StarWarsShip.getFragment('ship')}
    ${StarWarsDroid.getFragment('droid')}
  }
}

then you get fragment definitions under the machines. It looks like you are trapped and cannot check which of the objects is a type in an array of machines, so you cannot decide which component should be used.

+4
source share
1 answer

There is a field __typenamewith which you should be able to research the type of each record:

Query

fragment on Faction @relay(plural: true) {
  name,
  machines {
    __typename  # <-- add this
    ${StarWarsShip.getFragment('ship')}
    ${StarWarsDroid.getFragment('droid')}
  }
}

Application code

this.props.faction.machines.map(machine =>
  machine.__typename === 'Droid'
    ? <Droid droid={machine} />
    : <Ship ship={machine} />
);
+8

Source: https://habr.com/ru/post/1607230/