Skip to content

Commit a5b1ce6

Browse files
committed
03-Apollo Client with Pagination, Variables, Nested Objects and List Fields
1 parent 7a800c7 commit a5b1ce6

File tree

1 file changed

+63
-5
lines changed

1 file changed

+63
-5
lines changed

src/index.js

Lines changed: 63 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,17 +13,75 @@ const client = new ApolloClient({
1313
},
1414
});
1515

16-
const GET_ORGANIZATION = gql`
17-
{
18-
organization(login: "the-road-to-learn-react") {
16+
const GET_REPOSITORIES_OF_ORGANIZATION = gql`
17+
query($organization: String!, $cursor: String) {
18+
organization(login: $organization) {
1919
name
2020
url
21+
repositories(
22+
first: 5
23+
orderBy: { direction: DESC, field: STARGAZERS }
24+
after: $cursor
25+
) {
26+
edges {
27+
node {
28+
...repository
29+
}
30+
}
31+
pageInfo {
32+
endCursor
33+
hasNextPage
34+
}
35+
}
2136
}
2237
}
38+
fragment repository on Repository {
39+
name
40+
url
41+
}
2342
`;
2443

2544
client
2645
.query({
27-
query: GET_ORGANIZATION,
46+
query: GET_REPOSITORIES_OF_ORGANIZATION,
47+
variables: {
48+
organization: 'the-road-to-learn-react',
49+
cursor: undefined,
50+
},
51+
})
52+
// resolve first page
53+
.then(result => {
54+
const { pageInfo, edges } = result.data.organization.repositories;
55+
const { endCursor, hasNextPage } = pageInfo;
56+
57+
console.log('second page', edges.length);
58+
console.log('endCursor', endCursor);
59+
60+
return pageInfo;
61+
})
62+
// query second page
63+
.then(({ endCursor, hasNextPage }) => {
64+
if (!hasNextPage) {
65+
throw Error('no next page');
66+
}
67+
68+
return client.query({
69+
query: GET_REPOSITORIES_OF_ORGANIZATION,
70+
variables: {
71+
organization: 'the-road-to-learn-react',
72+
cursor: endCursor,
73+
},
74+
});
75+
})
76+
// resolve second page
77+
.then(result => {
78+
const { pageInfo, edges } = result.data.organization.repositories;
79+
const { endCursor, hasNextPage } = pageInfo;
80+
81+
console.log('second page', edges.length);
82+
console.log('endCursor', endCursor);
83+
84+
return pageInfo;
2885
})
29-
.then(console.log);
86+
// log error when there is no next page
87+
.catch(console.log);

0 commit comments

Comments
 (0)