Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactored to use infinite scroll instead of last 100 posts #16

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
"react": "18.2.0",
"react-dom": "18.2.0",
"react-hot-toast": "^2.4.0",
"react-intersection-observer": "^9.4.3",
"superjson": "1.9.1",
"zod": "^3.20.6"
},
Expand Down
2 changes: 1 addition & 1 deletion src/components/postview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import Link from "next/link";
import relativeTime from "dayjs/plugin/relativeTime";
dayjs.extend(relativeTime);

type PostWithUser = RouterOutputs["posts"]["getAll"][number];
type PostWithUser = RouterOutputs["posts"]["infiniteScroll"]["posts"][number];
export const PostView = (props: PostWithUser) => {
const { post, author } = props;
return (
Expand Down
66 changes: 45 additions & 21 deletions src/pages/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,12 @@ import { type NextPage } from "next";

import { api } from "~/utils/api";

import Image from "next/image";
import { LoadingPage, LoadingSpinner } from "~/components/loading";
import { useState } from "react";
import { useEffect, useState } from "react";
import { toast } from "react-hot-toast";
import { PageLayout } from "~/components/layout";
import { PostView } from "~/components/postview";

import { useInView } from "react-intersection-observer";
const CreatePostWizard = () => {
const { user } = useUser();

Expand All @@ -20,7 +19,7 @@ const CreatePostWizard = () => {
const { mutate, isLoading: isPosting } = api.posts.create.useMutation({
onSuccess: () => {
setInput("");
void ctx.posts.getAll.invalidate();
void ctx.posts.infiniteScroll.invalidate();
},
onError: (e) => {
const errorMessage = e.data?.zodError?.fieldErrors.content;
Expand All @@ -35,16 +34,17 @@ const CreatePostWizard = () => {
if (!user) return null;

return (

<div className="flex w-full gap-3">
<UserButton appearance={{
elements: {
userButtonAvatarBox: {
width: 56,
height: 56
}
}
}} />
<UserButton
appearance={{
elements: {
userButtonAvatarBox: {
width: 56,
height: 56,
},
},
}}
/>
<input
placeholder="Type some emojis!"
className="grow bg-transparent outline-none"
Expand Down Expand Up @@ -74,22 +74,46 @@ const CreatePostWizard = () => {
};

const Feed = () => {
const { data, isLoading: postsLoading } = api.posts.getAll.useQuery();
const {
data,
fetchNextPage,
hasNextPage,
isLoading: postsLoading,
isFetchingNextPage,
} = api.posts.infiniteScroll.useInfiniteQuery(
{ limit: 25 },
{ getNextPageParam: (lastPage) => lastPage.nextCursor }
);

const { ref, inView } = useInView();
useEffect(() => {
if (inView) {
void fetchNextPage();
}
}, [inView, fetchNextPage]);

if (postsLoading)
return (
<div className="flex grow">
<div className="flex flex-grow">
<LoadingPage />
</div>
);

if (!data) return <div>Something went wrong</div>;

return (
<div className="flex grow flex-col overflow-y-scroll">
{[...data, ...data, ...data, ...data].map((fullPost) => (
<PostView {...fullPost} key={fullPost.post.id} />
))}
<div className="relative flex flex-grow flex-col overflow-y-scroll">
{!!data &&
data.pages.map((page) =>
page.posts.map(({ post, author }) => (
<PostView post={post} author={author} key={post.id} />
))
)}
{!!isFetchingNextPage && !!hasNextPage && (
<div className="flex w-full justify-center">
<LoadingSpinner size={50} />
</div>
)}
<div ref={ref}> </div>
</div>
);
};
Expand All @@ -98,7 +122,7 @@ const Home: NextPage = () => {
const { isLoaded: userLoaded, isSignedIn } = useUser();

// Start fetching asap
api.posts.getAll.useQuery();
api.posts.infiniteScroll.useInfiniteQuery({ limit: 25 });

// Return empty div if user isn't loaded
if (!userLoaded) return <div />;
Expand Down
31 changes: 30 additions & 1 deletion src/server/api/routers/posts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ const addUserDataToPosts = async (posts: Post[]) => {
).map(filterUserForClient);

return posts.map((post) => {

const author = users.find((user) => user.id === post.authorId);

if (!author) {
Expand Down Expand Up @@ -82,6 +81,36 @@ export const postsRouter = createTRPCRouter({
return addUserDataToPosts(posts);
}),

infiniteScroll: publicProcedure
.input(
z.object({
limit: z.number(),
// cursor is a reference to the last item in the previous batch
// it's used to fetch the next batch
cursor: z.string().nullish(),
skip: z.number().optional(),
})
)
.query(async ({ ctx, input }) => {
const { limit, skip, cursor } = input;
const items = await ctx.prisma.post.findMany({
take: limit + 1,
skip: skip,
cursor: cursor ? { id: cursor } : undefined,
orderBy: [{ createdAt: "desc" }],
});
let nextCursor: typeof cursor | undefined = undefined;
if (items.length > limit) {
const nextItem = items.pop(); // return the last item from the array
nextCursor = nextItem?.id;
}
const posts = await addUserDataToPosts(items);
return {
posts,
nextCursor,
};
}),

getPostsByUserId: publicProcedure
.input(
z.object({
Expand Down