How to pass total count to the client in pageInfo

流过昼夜 提交于 2019-12-05 03:19:39

pageInfo is designed to represent information about the specific page, whereas the total number of items is really a property of the connection itself. We recommend adding a count field to the connection. You might query it with:

fragment on TodoList {
  tasks(first: 10) {
    count # <-- total number of tasks
    edges { ... }
    pageInfo { ... }
}

Relay supports arbitrary fields on a connection, so you're free to name this count, totalCount, etc.

Christine

Thank you @Joe Savona

He is absolutely right. Since it took me a moment to figure out how to actually add the property to the connection on the server site I thought I share that here as well:

var {connectionType: postsConnection} = connectionDefinitions({
  name: 'post',
  nodeType: qlPost,
  connectionFields: () => ({
    totalCount: {
      type: GraphQLInt,
      resolve: (connection) => connection.totalCount,
      description: `A count of the total number of objects in this connection, ignoring pagination.
This allows a client to fetch the first five objects by passing "5" as the
argument to "first", then fetch the total count so it could display "5 of 83",
for example.`
    }
  })
});

Hope that helps others.

Cheers

I used custom totalCount field on the connection for a while but it introduced a complexity I did not see at first (when updating connections after a mutation, you have to query it with the same args if you want it to update automatically).

Therefore I went back to having a count field next to each of my connections. In your exemple that means:

fragment on TodoList {
  taskCount
  tasks {
    edges { ... }
  }
}

And I created a small helper that creates it for me: https://github.com/rea-app/relay-connection-count

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