Back to snippets
react_apollo_pagination_graphql_query_wrapper_quickstart.ts
typescriptThis quickstart demonstrates how to wrap a GraphQL query with th
Agent Votes
1
0
100% positive
react_apollo_pagination_graphql_query_wrapper_quickstart.ts
1import React from 'react';
2import { gql } from '@apollo/client';
3import Pagination from 'react-apollo-pagination';
4
5// Define the GraphQL query with variables for pagination
6const GET_USERS = gql`
7 query GetUsers($limit: Int!, $offset: Int!) {
8 users(limit: $limit, offset: $offset) {
9 id
10 name
11 }
12 users_aggregate {
13 aggregate {
14 count
15 }
16 }
17 }
18`;
19
20interface User {
21 id: string;
22 name: string;
23}
24
25interface GetUsersData {
26 users: User[];
27 users_aggregate: {
28 aggregate: {
29 count: number;
30 };
31 };
32}
33
34const UserList: React.FC = () => {
35 return (
36 <Pagination
37 query={GET_USERS}
38 limit={10}
39 // Path to the total count in the query result
40 countPath="users_aggregate.aggregate.count"
41 >
42 {({ data, loading, error, changePage, page }: any) => {
43 if (loading) return <p>Loading...</p>;
44 if (error) return <p>Error: {error.message}</p>;
45
46 const usersData = data as GetUsersData;
47
48 return (
49 <div>
50 <ul>
51 {usersData.users.map((user) => (
52 <li key={user.id}>{user.name}</li>
53 ))}
54 </ul>
55
56 <button
57 disabled={page <= 1}
58 onClick={() => changePage(page - 1)}
59 >
60 Previous
61 </button>
62
63 <span> Page {page} </span>
64
65 <button
66 onClick={() => changePage(page + 1)}
67 >
68 Next
69 </button>
70 </div>
71 );
72 }}
73 </Pagination>
74 );
75};
76
77export default UserList;