Merge pull request #25 from aaronpo97/beer-infinite-scroll

Feature: Add infinite scrolling to beer index page
This commit is contained in:
Aaron Po
2023-04-16 23:29:43 -04:00
committed by GitHub
12 changed files with 262 additions and 63 deletions

View File

@@ -8,7 +8,7 @@
"start": "next start", "start": "next start",
"lint": "next lint", "lint": "next lint",
"format": "npx prettier . --write", "format": "npx prettier . --write",
"seed": "npx ts-node ./prisma/seed/index.ts" "seed": "npx ts-node ./src/prisma/seed/index.ts"
}, },
"dependencies": { "dependencies": {
"@hapi/iron": "^7.0.1", "@hapi/iron": "^7.0.1",

View File

@@ -20,8 +20,8 @@ const BeerPostLikeButton: FC<{
try { try {
setLoading(true); setLoading(true);
await sendLikeRequest(beerPostId); await sendLikeRequest(beerPostId);
await mutateCount();
await mutateLikeStatus(); await Promise.all([mutateCount(), mutateLikeStatus()]);
setLoading(false); setLoading(false);
} catch (e) { } catch (e) {
setLoading(false); setLoading(false);

View File

@@ -1,13 +1,19 @@
import Link from 'next/link'; import Link from 'next/link';
import { FC } from 'react'; import { FC, useContext } from 'react';
import Image from 'next/image'; import Image from 'next/image';
import beerPostQueryResult from '@/services/BeerPost/schema/BeerPostQueryResult'; import beerPostQueryResult from '@/services/BeerPost/schema/BeerPostQueryResult';
import { z } from 'zod'; import { z } from 'zod';
import UserContext from '@/contexts/userContext';
import useGetLikeCount from '@/hooks/useGetLikeCount';
import BeerPostLikeButton from '../BeerById/BeerPostLikeButton';
const BeerCard: FC<{ post: z.infer<typeof beerPostQueryResult> }> = ({ post }) => { const BeerCard: FC<{ post: z.infer<typeof beerPostQueryResult> }> = ({ post }) => {
const { user } = useContext(UserContext);
const { mutate, likeCount } = useGetLikeCount(post.id);
return ( return (
<div className="card bg-base-300" key={post.id}> <div className="card card-compact bg-base-300" key={post.id}>
<figure className="card-image h-96"> <figure className="h-96">
{post.beerImages.length > 0 && ( {post.beerImages.length > 0 && (
<Image <Image
src={post.beerImages[0].path} src={post.beerImages[0].path}
@@ -18,12 +24,31 @@ const BeerCard: FC<{ post: z.infer<typeof beerPostQueryResult> }> = ({ post }) =
)} )}
</figure> </figure>
<div className="card-body space-y-3"> <div className="card-body justify-between">
<div className="space-y-1">
<Link href={`/beers/${post.id}`}>
<h2 className="link-hover link truncate text-2xl font-bold lg:text-3xl">
{post.name}
</h2>
</Link>
<Link href={`/breweries/${post.brewery.id}`}>
<h3 className="text-md link-hover link truncate lg:text-xl">
{post.brewery.name}
</h3>
</Link>
</div>
<div> <div>
<h2 className="text-3xl font-bold"> <div>
<Link href={`/beers/${post.id}`}>{post.name}</Link> <p className="text-md lg:text-xl">{post.type.name}</p>
</h2> <div className="space-x-3">
<h3 className="text-xl font-semibold">{post.brewery.name}</h3> <span className="text-sm lg:text-lg">{post.abv}% ABV</span>
<span className="text-sm lg:text-lg">{post.ibu} IBU</span>
</div>
</div>
<div className="flex justify-between">
liked by {likeCount} users
{user && <BeerPostLikeButton beerPostId={post.id} mutateCount={mutate} />}
</div>
</div> </div>
</div> </div>
</div> </div>

View File

@@ -0,0 +1,26 @@
import { FC } from 'react';
const BeerPostLoadingCard: FC = () => {
return (
<div className="card bg-base-300">
<figure className="h-96 border-8 border-base-300 bg-base-300">
<div className="h-full w-full animate-pulse rounded-md bg-base-100" />
</figure>
<div className="card-body h-52">
<div className="flex animate-pulse space-x-4">
<div className="flex-1 space-y-4 py-1">
<div className="h-4 w-3/4 rounded bg-base-100" />
<div className="space-y-2">
<div className="h-4 rounded bg-base-100" />
<div className="h-4 w-5/6 rounded bg-base-100" />
<div className="h-4 w-5/6 rounded bg-base-100" />
<div className="h-4 rounded bg-base-100" />
</div>
</div>
</div>
</div>
</div>
);
};
export default BeerPostLoadingCard;

62
src/hooks/useBeerPosts.ts Normal file
View File

@@ -0,0 +1,62 @@
import beerPostQueryResult from '@/services/BeerPost/schema/BeerPostQueryResult';
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
import useSWRInfinite from 'swr/infinite';
import { z } from 'zod';
/**
* A custom hook using SWR to fetch beer posts from the API.
*
* @param options The options to use when fetching beer posts.
* @param options.pageSize The number of beer posts to fetch per page.
* @returns An object containing the beer posts, page count, and loading state.
*/
const useBeerPosts = ({ pageSize }: { pageSize: number }) => {
const fetcher = async (url: string) => {
const response = await fetch(url);
if (!response.ok) {
throw new Error(response.statusText);
}
const json = await response.json();
const count = response.headers.get('X-Total-Count');
const parsed = APIResponseValidationSchema.safeParse(json);
if (!parsed.success) {
throw new Error('API response validation failed');
}
const parsedPayload = z.array(beerPostQueryResult).safeParse(parsed.data.payload);
if (!parsedPayload.success) {
throw new Error('API response validation failed');
}
const pageCount = Math.ceil(parseInt(count as string, 10) / pageSize);
return {
beerPosts: parsedPayload.data,
pageCount,
};
};
const { data, error, isLoading, setSize, size } = useSWRInfinite(
(index) => `/api/beers?pageNum=${index + 1}&pageSize=${pageSize}`,
fetcher,
);
const beerPosts = data?.flatMap((d) => d.beerPosts) ?? [];
const pageCount = data?.[0].pageCount ?? 0;
const isLoadingMore = size > 0 && data && typeof data[size - 1] === 'undefined';
const isAtEnd = !(size < data?.[0].pageCount!);
return {
beerPosts,
pageCount,
size,
setSize,
isLoading,
isLoadingMore,
isAtEnd,
error: error as unknown,
};
};
export default useBeerPosts;

View File

@@ -0,0 +1,54 @@
import validateRequest from '@/config/nextConnect/middleware/validateRequest';
import DBClient from '@/prisma/DBClient';
import getAllBeerPosts from '@/services/BeerPost/getAllBeerPosts';
import APIResponseValidationSchema from '@/validation/APIResponseValidationSchema';
import { NextApiRequest, NextApiResponse } from 'next';
import { createRouter } from 'next-connect';
import { z } from 'zod';
interface GetBeerPostsRequest extends NextApiRequest {
query: {
pageNum: string;
pageSize: string;
};
}
const getBeerPosts = async (
req: GetBeerPostsRequest,
res: NextApiResponse<z.infer<typeof APIResponseValidationSchema>>,
) => {
const pageNum = parseInt(req.query.pageNum, 10);
const pageSize = parseInt(req.query.pageSize, 10);
const beerPosts = await getAllBeerPosts(pageNum, pageSize);
const beerPostCount = await DBClient.instance.beerPost.count();
res.setHeader('X-Total-Count', beerPostCount);
res.status(200).json({
message: 'Beer posts retrieved successfully',
statusCode: 200,
payload: beerPosts,
success: true,
});
};
const router = createRouter<
GetBeerPostsRequest,
NextApiResponse<z.infer<typeof APIResponseValidationSchema>>
>();
router.get(
validateRequest({
querySchema: z.object({
pageNum: z.string().regex(/^\d+$/),
pageSize: z.string().regex(/^\d+$/),
}),
}),
getBeerPosts,
);
const handler = router.handler();
export default handler;

View File

@@ -61,7 +61,7 @@ const BeerByIdPage: NextPage<BeerPageProps> = ({ beerPost, beerRecommendations }
</Carousel> </Carousel>
<div className="mb-12 mt-10 flex w-full items-center justify-center "> <div className="mb-12 mt-10 flex w-full items-center justify-center ">
<div className="w-11/12 space-y-3 xl:w-9/12"> <div className="w-11/12 space-y-3 xl:w-9/12 2xl:w-8/12">
<BeerInfoHeader beerPost={beerPost} /> <BeerInfoHeader beerPost={beerPost} />
{isDesktop ? ( {isDesktop ? (

View File

@@ -1,44 +1,47 @@
import { GetServerSideProps, NextPage } from 'next'; import { NextPage } from 'next';
import getAllBeerPosts from '@/services/BeerPost/getAllBeerPosts';
import { useRouter } from 'next/router';
import DBClient from '@/prisma/DBClient';
import Layout from '@/components/ui/Layout'; import Layout from '@/components/ui/Layout';
import BeerIndexPaginationBar from '@/components/BeerIndex/BeerIndexPaginationBar';
import BeerCard from '@/components/BeerIndex/BeerCard'; import BeerCard from '@/components/BeerIndex/BeerCard';
import beerPostQueryResult from '@/services/BeerPost/schema/BeerPostQueryResult';
import Head from 'next/head'; import Head from 'next/head';
import { z } from 'zod';
import Link from 'next/link'; import Link from 'next/link';
import UserContext from '@/contexts/userContext'; import UserContext from '@/contexts/userContext';
import { useContext } from 'react'; import { MutableRefObject, useContext, useRef } from 'react';
interface BeerPageProps { import { useInView } from 'react-intersection-observer';
initialBeerPosts: z.infer<typeof beerPostQueryResult>[]; import Spinner from '@/components/ui/Spinner';
pageCount: number;
}
const BeerPage: NextPage<BeerPageProps> = ({ initialBeerPosts, pageCount }) => { import useBeerPosts from '@/hooks/useBeerPosts';
const router = useRouter(); import BeerPostLoadingCard from '@/components/BeerIndex/BeerPostLoadingCard';
const { query } = router; import { FaArrowUp } from 'react-icons/fa';
const BeerPage: NextPage = () => {
const { user } = useContext(UserContext); const { user } = useContext(UserContext);
const pageNum = parseInt(query.page_num as string, 10) || 1; const PAGE_SIZE = 2;
const { beerPosts, setSize, size, isLoading, isLoadingMore, isAtEnd } = useBeerPosts({
pageSize: PAGE_SIZE,
});
const { ref: lastBeerPostRef } = useInView({
onChange: (visible) => {
if (!visible || isAtEnd) return;
setSize(size + 1);
},
});
const pageRef: MutableRefObject<HTMLDivElement | null> = useRef(null);
return ( return (
<Layout> <Layout>
<Head> <Head>
<title>Beer</title> <title>Beer</title>
<meta name="description" content="Beer posts" /> <meta name="description" content="Beer posts" />
</Head> </Head>
<div className="flex items-center justify-center bg-base-100"> <div className="flex items-center justify-center bg-base-100" ref={pageRef}>
<div className="my-10 flex w-10/12 flex-col space-y-4"> <div className="my-10 flex w-11/12 flex-col space-y-4 lg:w-8/12 2xl:w-7/12">
<header className="my-10 flex justify-between"> <header className="my-10 flex justify-between">
<div className="space-y-2"> <div className="space-y-2">
<h1 className="text-6xl font-bold">The Biergarten Index</h1> <h1 className="text-6xl font-bold">The Biergarten Index</h1>
<h2 className="text-2xl font-bold">
Page {pageNum} of {pageCount}
</h2>
</div> </div>
{!!user && ( {!!user && (
<div> <div>
@@ -48,31 +51,61 @@ const BeerPage: NextPage<BeerPageProps> = ({ initialBeerPosts, pageCount }) => {
</div> </div>
)} )}
</header> </header>
<div className="grid gap-5 md:grid-cols-2 xl:grid-cols-3"> <div className="grid gap-6 xl:grid-cols-2">
{initialBeerPosts.map((post) => { {!!beerPosts.length && !isLoading && (
return <BeerCard post={post} key={post.id} />; <>
})} {beerPosts.map((beerPost, i) => {
</div> return (
<div className="flex justify-center"> <div
<BeerIndexPaginationBar pageNum={pageNum} pageCount={pageCount} /> key={beerPost.id}
ref={beerPosts.length === i + 1 ? lastBeerPostRef : undefined}
>
<BeerCard post={beerPost} />
</div>
);
})}
</>
)}
{(isLoading || isLoadingMore) && (
<>
{Array.from({ length: PAGE_SIZE }, (_, i) => (
<BeerPostLoadingCard key={i} />
))}
</>
)}
</div> </div>
{(isLoading || isLoadingMore) && (
<div className="flex h-32 w-full items-center justify-center">
<Spinner size="sm" />
</div>
)}
{isAtEnd && !isLoading && (
<div className="flex h-20 items-center justify-center text-center">
<div
className="tooltip tooltip-bottom"
data-tip="Scroll back to top of page."
>
<button
type="button"
className="btn-ghost btn-sm btn"
aria-label="Scroll back to top of page."
onClick={() => {
pageRef.current?.scrollIntoView({
behavior: 'smooth',
});
}}
>
<FaArrowUp />
</button>
</div>
</div>
)}
</div> </div>
</div> </div>
</Layout> </Layout>
); );
}; };
export const getServerSideProps: GetServerSideProps<BeerPageProps> = async (context) => {
const { query } = context;
const pageNumber = parseInt(query.page_num as string, 10) || 1;
const pageSize = 12;
const numberOfPosts = await DBClient.instance.beerPost.count();
const pageCount = numberOfPosts ? Math.ceil(numberOfPosts / pageSize) : 0;
const beerPosts = await getAllBeerPosts(pageNumber, pageSize);
return {
props: { initialBeerPosts: JSON.parse(JSON.stringify(beerPosts)), pageCount },
};
};
export default BeerPage; export default BeerPage;

View File

@@ -1,5 +1,5 @@
import { PrismaClient } from '@prisma/client'; import { PrismaClient } from '@prisma/client';
import { NODE_ENV } from '@/config/env'; import { NODE_ENV } from '../config/env';
const globalForPrisma = global as unknown as { prisma: PrismaClient }; const globalForPrisma = global as unknown as { prisma: PrismaClient };

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 104 KiB

View File

@@ -3,5 +3,5 @@
@tailwind utilities; @tailwind utilities;
.card { .card {
@apply shadow-md @apply shadow-md card-compact bg-base-300
} }

View File

@@ -12,7 +12,7 @@ const darkTheme = {
warning: 'hsl(50, 98%, 50%)', warning: 'hsl(50, 98%, 50%)',
'primary-content': 'hsl(0, 0%, 98%)', 'primary-content': 'hsl(0, 0%, 98%)',
'error-content': 'hsl(0, 0%, 98%)', 'error-content': 'hsl(0, 0%, 98%)',
'base-100': 'hsl(190, 4%, 9%)', 'base-100': 'hsl(190, 4%, 11%)',
'base-200': 'hsl(190, 4%, 8%)', 'base-200': 'hsl(190, 4%, 8%)',
'base-300': 'hsl(190, 4%, 5%)', 'base-300': 'hsl(190, 4%, 5%)',
}, },
@@ -28,11 +28,11 @@ const pastelTheme = {
info: 'hsl(163, 40%, 79%)', info: 'hsl(163, 40%, 79%)',
success: 'hsl(93, 27%, 73%)', success: 'hsl(93, 27%, 73%)',
warning: 'hsl(40, 76%, 73%)', warning: 'hsl(40, 76%, 73%)',
'primary-content': 'hsl(0, 0%, 12%)', 'primary-content': 'hsl(0, 0%, 0%)',
'error-content': 'hsl(0, 0%, 12%)', 'error-content': 'hsl(0, 0%, 0%)',
'base-100': 'hsl(0, 0%, 85%)', 'base-100': 'hsl(0, 0%, 94%)',
'base-200': 'hsl(0, 0%, 82%)', 'base-200': 'hsl(0, 0%, 90%)',
'base-300': 'hsl(0, 0%, 78%)', 'base-300': 'hsl(0, 0%, 85%)',
}, },
}; };