Feat: Update beer recs to be loaded on the client side

This commit is contained in:
Aaron William Po
2023-05-14 14:55:02 -04:00
parent 2d2cd8189a
commit 50c3e1a82b
10 changed files with 308 additions and 80 deletions

View File

@@ -6,6 +6,7 @@ import { FC, MutableRefObject, useContext, useRef } from 'react';
import { z } from 'zod';
import useBeerPostComments from '@/hooks/data-fetching/beer-comments/useBeerPostComments';
import { useRouter } from 'next/router';
import CreateCommentValidationSchema from '@/services/types/CommentSchema/CreateCommentValidationSchema';
import BeerCommentForm from './BeerCommentForm';
import LoadingComponent from './LoadingComponent';
@@ -20,29 +21,25 @@ const BeerPostCommentsSection: FC<BeerPostCommentsSectionProps> = ({ beerPost })
const router = useRouter();
const pageNum = parseInt(router.query.comments_page as string, 10) || 1;
const PAGE_SIZE = 4;
const PAGE_SIZE = 15;
const { comments, isLoading, mutate, setSize, size, isLoadingMore, isAtEnd } =
useBeerPostComments({
id: beerPost.id,
pageNum,
pageSize: PAGE_SIZE,
});
useBeerPostComments({ id: beerPost.id, pageNum, pageSize: PAGE_SIZE });
const commentSectionRef: MutableRefObject<HTMLDivElement | null> = useRef(null);
async function handleDeleteRequest(id: string) {
const handleDeleteRequest = async (id: string) => {
const response = await fetch(`/api/beer-comments/${id}`, { method: 'DELETE' });
if (!response.ok) {
throw new Error('Failed to delete comment.');
}
}
};
async function handleEditRequest(
const handleEditRequest = async (
id: string,
data: { content: string; rating: number },
) {
data: z.infer<typeof CreateCommentValidationSchema>,
) => {
const response = await fetch(`/api/beer-comments/${id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
@@ -52,7 +49,7 @@ const BeerPostCommentsSection: FC<BeerPostCommentsSectionProps> = ({ beerPost })
if (!response.ok) {
throw new Error('Failed to update comment.');
}
}
};
return (
<div className="w-full space-y-3" ref={commentSectionRef}>

View File

@@ -1,40 +1,101 @@
import BeerRecommendationQueryResult from '@/services/BeerPost/schema/BeerRecommendationQueryResult';
import Link from 'next/link';
import { FunctionComponent } from 'react';
import { FC, MutableRefObject, useRef } from 'react';
import { useInView } from 'react-intersection-observer';
import { z } from 'zod';
import useBeerRecommendations from '@/hooks/data-fetching/beer-posts/useBeerRecommendations';
import beerPostQueryResult from '@/services/BeerPost/schema/BeerPostQueryResult';
import debounce from 'lodash/debounce';
import BeerRecommendationLoadingComponent from './BeerRecommendationLoadingComponent';
const BeerRecommendationsSection: FC<{
beerPost: z.infer<typeof beerPostQueryResult>;
}> = ({ beerPost }) => {
const PAGE_SIZE = 10;
const { beerPosts, isAtEnd, isLoadingMore, setSize, size } = useBeerRecommendations({
beerPost,
pageSize: PAGE_SIZE,
});
const { ref: penultimateBeerPostRef } = useInView({
/**
* When the last beer post comes into view, call setSize from useBeerPostsByBrewery to
* load more beer posts.
*/
onChange: (visible) => {
if (!visible || isAtEnd) return;
debounce(() => setSize(size + 1), 200)();
},
});
const beerRecommendationsRef: MutableRefObject<HTMLDivElement | null> = useRef(null);
interface BeerRecommendationsProps {
beerRecommendations: BeerRecommendationQueryResult[];
}
const BeerRecommendations: FunctionComponent<BeerRecommendationsProps> = ({
beerRecommendations,
}) => {
return (
<div className="card sticky top-2 h-full overflow-y-scroll">
<div className="card-body space-y-3">
{beerRecommendations.map((beerPost) => (
<div key={beerPost.id} className="w-full">
<div className="card h-full" ref={beerRecommendationsRef}>
<div className="card-body">
<>
<div className="my-2 flex flex-row items-center justify-between">
<div>
<Link className="link-hover" href={`/beers/${beerPost.id}`} scroll={false}>
<h2 className="truncate text-lg font-bold lg:text-2xl">
{beerPost.name}
</h2>
</Link>
<Link href={`/breweries/${beerPost.brewery.id}`} className="link-hover">
<p className="text-md truncate font-semibold lg:text-xl">
{beerPost.brewery.name}
</p>
</Link>
</div>
<div className="space-x-3 text-sm lg:text-lg">
<span>{beerPost.abv}% ABV</span>
<span>{beerPost.ibu} IBU</span>
<h3 className="text-3xl font-bold">Also check out</h3>
</div>
</div>
))}
{!!beerPosts.length && (
<div className="space-y-5">
{beerPosts.map((post, index) => {
const isPenultimateBeerPost = index === beerPosts.length - 2;
/**
* Attach a ref to the second last beer post in the list. When it comes
* into view, the component will call setSize to load more beer posts.
*/
return (
<div
ref={isPenultimateBeerPost ? penultimateBeerPostRef : undefined}
key={post.id}
>
<div className="flex flex-col">
<Link className="link-hover link" href={`/beers/${post.id}`}>
<span className="text-xl font-semibold">{post.name}</span>
</Link>
<Link
className="link-hover link"
href={`/breweries/${post.brewery.id}`}
>
<span className="text-lg font-semibold">{post.brewery.name}</span>
</Link>
</div>
<div>
<div>
<span className="text-lg font-medium">{post.type.name}</span>
</div>
<div className="space-x-2">
<span>{post.abv}% ABV</span>
<span>{post.ibu} IBU</span>
</div>
</div>
</div>
);
})}
</div>
)}
{
/**
* If there are more beer posts to load, show a loading component with a
* skeleton loader and a loading spinner.
*/
!!isLoadingMore && !isAtEnd && (
<BeerRecommendationLoadingComponent length={PAGE_SIZE} />
)
}
</>
</div>
</div>
);
};
export default BeerRecommendations;
export default BeerRecommendationsSection;

View File

@@ -1,10 +1,11 @@
import UseBeerPostsByBrewery from '@/hooks/data-fetching/beer-posts/useBeerPostsByBrewery';
import BreweryPostQueryResult from '@/services/BreweryPost/types/BreweryPostQueryResult';
import Link from 'next/link';
import { FC } from 'react';
import { FC, MutableRefObject, useContext, useRef } from 'react';
import { useInView } from 'react-intersection-observer';
import { z } from 'zod';
import { FaPlus } from 'react-icons/fa';
import UserContext from '@/contexts/userContext';
import BeerRecommendationLoadingComponent from '../BeerById/BeerRecommendationLoadingComponent';
interface BreweryCommentsSectionProps {
@@ -13,6 +14,8 @@ interface BreweryCommentsSectionProps {
const BreweryBeersSection: FC<BreweryCommentsSectionProps> = ({ breweryPost }) => {
const PAGE_SIZE = 2;
const { user } = useContext(UserContext);
const { beerPosts, isAtEnd, isLoadingMore, setSize, size } = UseBeerPostsByBrewery({
breweryId: breweryPost.id,
pageSize: PAGE_SIZE,
@@ -28,8 +31,10 @@ const BreweryBeersSection: FC<BreweryCommentsSectionProps> = ({ breweryPost }) =
},
});
const beerRecommendationsRef: MutableRefObject<HTMLDivElement | null> = useRef(null);
return (
<div className="card">
<div className="card h-full" ref={beerRecommendationsRef}>
<div className="card-body">
<>
<div className="my-2 flex flex-row items-center justify-between">
@@ -37,13 +42,15 @@ const BreweryBeersSection: FC<BreweryCommentsSectionProps> = ({ breweryPost }) =
<h3 className="text-3xl font-bold">Brews</h3>
</div>
<div>
<Link
className={`btn-ghost btn-sm btn gap-2 rounded-2xl outline`}
href={`/breweries/${breweryPost.id}/beers/create`}
>
<FaPlus className="text-xl" />
Add Beer
</Link>
{user && (
<Link
className={`btn-ghost btn-sm btn gap-2 rounded-2xl outline`}
href={`/breweries/${breweryPost.id}/beers/create`}
>
<FaPlus className="text-xl" />
Add Beer
</Link>
)}
</div>
</div>

View File

@@ -49,9 +49,10 @@ const CommentsComponent: FC<CommentsComponentProps> = ({
handleEditRequest,
}) => {
const { ref: penultimateCommentRef } = useInView({
threshold: 0.1,
/**
* When the second last comment comes into view, call setSize from useBeerPostComments
* to load more comments.
* When the last comment comes into view, call setSize from useBeerPostComments to
* load more comments.
*/
onChange: (visible) => {
if (!visible || isAtEnd) return;
@@ -62,9 +63,9 @@ const CommentsComponent: FC<CommentsComponentProps> = ({
return (
<>
{!!comments.length && (
<div className="card bg-base-300 pb-6">
<div className="card h-full bg-base-300 pb-6">
{comments.map((comment, index) => {
const isPenultimateComment = index === comments.length - 2;
const isLastComment = index === comments.length - 1;
/**
* Attach a ref to the last comment in the list. When it comes into view, the
@@ -72,7 +73,7 @@ const CommentsComponent: FC<CommentsComponentProps> = ({
*/
return (
<div
ref={isPenultimateComment ? penultimateCommentRef : undefined}
ref={isLastComment ? penultimateCommentRef : undefined}
key={comment.id}
>
<CommentCardBody