How to get RelayJS to understand that a response from GraphQL is an array of items, not just a single item

ぐ巨炮叔叔 提交于 2019-11-29 09:35:28

问题


I have a GraphQL server running with a schema roughly like this:

type Card {
  id: String!
  name: String
}

type Query {
  card(name: String!): Card
  cards(power: String): [Card]
}

Notice that I have a query on a single card, but also on multiple cards. When I use the GraphIQl UI and make a query like this "query {cards { name }}" I get back an array of cards, as expected.

However, I have a RelayContainer that is making the same query, but the props that come back are just the first result, rather than an array of results.

class MyApp extends React.Component {
  render() {
    return (
      <div>
        <h1> Hello world!</h1>
        <CardList cards={this.props.cards} />
      </div>
    );
  }
}

export default Relay.createContainer(MyApp, {
  fragments: {
    card: () => Relay.QL`
      fragment on Card {
        name
      }
    `,
    cards: () => Relay.QL`
      fragment on Card {
        ${CardList.getFragment('cards')}
      }
    `
  },
});

and the CardList component is set up with the Container like this:

class CardList extends React.Component {
  render() {
    return <div>{this.props.cards}</div> // UNEXPECTED - this.props.cards is the first card, not an array for me to .map over
  }
}

export default Relay.createContainer(CardList, {
  fragments: {
    cards: () => Relay.QL`
      fragment on Card {
        name
      }
    `,
  },
});

Anybody have any suggestions? This is day 2 of me diving into GraphQL and Relay, so I might be making a very basic mistake for all I know.


回答1:


You probably want a @relay(plural: true) directive on your cards query fragment. There is an example of a plural field in action in the Star Wars example in the Relay repo.

If you care about pagination, though, you probably want a connection instead of a plural field. Connections are described in the Relay docs and implemented in graphql-relay-js.



来源:https://stackoverflow.com/questions/32491117/how-to-get-relayjs-to-understand-that-a-response-from-graphql-is-an-array-of-ite

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!