Guest User

Untitled

a guest
Feb 12th, 2024
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.00 KB | None | 0 0
  1. import { useQuery, gql} from "@apollo/client";
  2. import Link from "next/link";
  3.  
  4.  
  5. const GET_POSTS = gql`
  6. query getPosts($first: Int!, $after: String) {
  7. posts(first: $first, after: $after) {
  8. pageInfo {
  9. hasNextPage
  10. endCursor
  11. }
  12. edges {
  13. node {
  14. id
  15. databaseId
  16. title
  17. slug
  18. }
  19. }
  20. }
  21. }
  22. `;
  23.  
  24. const BATCH_SIZE = 4;
  25.  
  26. export default function LoadMorePost() {
  27. const { data, loading, error, fetchMore } = useQuery(GET_POSTS, {
  28. variables: { first: BATCH_SIZE, after: null },
  29. notifyOnNetworkStatusChange: true,
  30. });
  31.  
  32. if (error) {
  33. return <p>Sorry, an error happened. Reload Please</p>;
  34. }
  35.  
  36. if (!data && loading) {
  37. return <p>Loadding...</p>;
  38. }
  39.  
  40. if (!data?.posts.edges.length) {
  41. return <p>no posts have been published</p>;
  42. }
  43.  
  44. const posts = data.posts.edges.map((edge) => edge.node);
  45. const haveMorePosts = Boolean(data?.posts?.pageInfo?.hasNextPage);
  46.  
  47. return (
  48.  
  49. <>
  50.  
  51. <ul style={{ padding: "0" }}>
  52. {posts.map((post) => {
  53. const { databaseId, title, slug } = post;
  54. return (
  55. <li
  56. key={databaseId}
  57. style={{
  58. border: "2px solid #ededed",
  59. borderRadius: "10px",
  60. padding: "2rem",
  61. listStyle: "none",
  62. marginBottom: "1rem",
  63. }}
  64. >
  65. <Link href={`/posts/${slug}`}>{title}</Link>
  66. </li>
  67. );
  68. })}
  69. </ul>
  70. {haveMorePosts ? (
  71. <form
  72. method="post"
  73. onSubmit={(event) => {
  74. event.preventDefault();
  75. fetchMore({ variables: { after: data.posts.pageInfo.endCursor } });
  76. }}
  77. >
  78. <button type="submit">
  79. {loading ? "Loading..." : "Load more"}
  80. </button>
  81. </form>
  82. ) : (
  83. <p>✅ All posts loaded.</p>
  84. )}
  85.  
  86. </>
  87. );
  88. }
  89.  
Advertisement
Add Comment
Please, Sign In to add comment