I am trying to paginate 2 relay-style fields posts_connection
and comments_connection
For instance, the query is extremely simple,
const QUERY = gql `
PostsQuery($comments_first: Int, commments_after: String) {
posts_connection {
edges {
node {
...INFO_ABOUT_A_POST
comments_connection(first:$comments_first, after:$commments_after) {
edges {
node {
...INFO_ABOUT_A_COMMENT
}
}
}
}
}
}
}
`
To do this with Apollo client, we configure the cache using relayStylePagination()
, as in Cursor-based pagination - Apollo GraphQL Docs
const cache = new InMemoryCache({
typePolicies: {
Query: {
fields: {
posts_connection: relayStylePagination(),
},
},
posts: { // posts is the type of a single post node
fields: {
keyFields: ["postid"],
comments_connection: relayStylePagination()
}
},
comments: {
keyFields: ["commentid"],
},
}
}
My process is
1) Run the initial query,
data has a single initial comment, COMMENT1
2) fetchMore comments
fetchMore({variables : {comments_after:PREVIOUS_END_CURSOR} })
We should get a new comment COMMENT2
The issue: data does not merge the edges properly. We want data.posts_connection.[...].comments_connection.edges = [COMMENT1, COMMENT2]
.
Instead, data.posts_connection.[...].comments_connection.edges = [COMMENT2]
.
One can verify this by looking in the cache.
I believe this is caused by the simple merging done in the relayStylePagination
function in the source code
const edges = [
...prefix,
...incomingEdges,
...suffix,
];
One possible explanation:
I think the issue is that a simple array combination like this is might not be enough, since we have nested connections. I think merging edges should require some sort of mergedeep
function, that merges connections lower down in the query.
What is causing the edges to get overwritten, and how do I fix this, and merge the edges?