Skip to content

Instantly share code, notes, and snippets.

@kellenmace
Created May 27, 2021 14:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kellenmace/ff97d014f68c7b1a0a4bdbc209b32a87 to your computer and use it in GitHub Desktop.
Save kellenmace/ff97d014f68c7b1a0a4bdbc209b32a87 to your computer and use it in GitHub Desktop.
import { gql, useLazyQuery } from "@apollo/client";
import Layout from "../components/Layout";
interface Post {
databaseId: number;
title: string;
};
interface PostEdge {
node: Post;
};
const POSTS_PER_PAGE = 10;
const GET_POSTS = gql`
query getPosts($first: Int!, $after: String) {
posts(first: $first, after: $after) {
pageInfo {
hasNextPage
endCursor
}
edges {
node {
id
databaseId
title
slug
}
}
}
}
`;
export default function Blog(props) {
const { initialPosts, initialEndCursor, initialHasNextPage } = props;
const [fetchMorePosts, { called, loading, error, data }] = useLazyQuery(GET_POSTS, {
notifyOnNetworkStatusChange: true,
});
const runtimePosts = data?.posts?.edges?.map((edge: PostEdge) => edge.node) || [];
const posts = [...initialPosts, ...runtimePosts];
const havePosts = Boolean(posts.length);
const haveMorePosts = called ? Boolean(data?.posts?.pageInfo?.hasNextPage) : initialHasNextPage;
return (
<Layout>
<h1>Blog</h1>
{!havePosts && loading ? (
<p>Loading...</p>
) : error ? (
<p>An error has occurred.</p>
) : !havePosts ? (
<p>No posts found.</p>
) : (
posts.map((post: Post) => {
return (
<article key={post.databaseId} style={{ border: "2px solid #eee", padding: "1rem", marginBottom: "1rem", borderRadius: "10px" }}>
<h2>{post.title}</h2>
</article>
);
})
)}
{havePosts ? (
haveMorePosts ? (
<form onSubmit={event => {
event.preventDefault();
fetchMorePosts({
variables: {
first: 5,
after: data?.posts?.pageInfo?.endCursor ?? initialEndCursor,
}
});
}}>
<button type="submit" disabled={loading}>
{loading ? "Loading..." : "Load more"}
</button>
</form>
) : (
<p>✅ All posts loaded.</p>
)
) : null}
</Layout>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment