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

feat: add infinite query example #69

Open
wants to merge 7 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
123 changes: 123 additions & 0 deletions src/feature/infinite-query/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
import { useEffect, useRef } from 'react';
import { trpc } from 'utils/trpc';

export default function Page() {
const bottomOfPage = useRef<HTMLDivElement>(null);
const myQuery = trpc.infiniteQueryRouter.getItems.useInfiniteQuery(
{
limit: 10,
},
{
getNextPageParam: (lastPage) => lastPage.nextCursor,
},
);
const { data: posts, fetchNextPage, isFetchingNextPage } = myQuery;

// Setup optional intersection observer to fetch next page when bottom of page is reached.
// This is not needed if you have a "Load more" button or similar.
useEffect(() => {
const bottomDiv = bottomOfPage.current;
const observer = new IntersectionObserver(
(entries) => {
if (entries[0].isIntersecting) {
fetchNextPage();
}
},
{ threshold: 1 },
);
if (bottomDiv) {
observer.observe(bottomDiv);
}
return () => {
if (bottomDiv) {
observer.unobserve(bottomDiv);
}
};
}, [fetchNextPage]);

return (
<>
<h2 className="text-3xl font-bold py-8">Top Recent Posts from /r/Aww</h2>
<div className="flex flex-col space-y-3 py-2 min-h-screen">
{posts ? (
posts.pages.map((page) => {
return page.items.data.children.map((post) => (
<article
key={post.data.id}
className="bg-white shadow overflow-hidden sm:rounded-lg p-4 flex justify-start items-center space-x-2"
>
{/* upvote/downvote buttons */}
<div className="flex flex-col gap-1">
<button className="w-6 h-6 flex items-center justify-center bg-gray-200 rounded-md group">
<svg
className="w-4 h-4 text-gray-500 group-hover:text-orange-500"
fill="currentColor"
viewBox="0 0 20 20"
xmlns="http://www.w3.org/2000/svg"
>
<path
fillRule="evenodd"
d="M10 17a1 1 0 01-1-1V7.414l-2.293 2.293a1 1 0 01-1.32.083l-.094-.083a1 1 0 01-.083-1.32l.083-.094 4-4a1 1 0 011.32-.083l.094.083 4 4a1 1 0 01-1.32 1.497l-.094-.083L11 7.414V16a1 1 0 01-1 1z"
clipRule="evenodd"
/>
</svg>
</button>
<button className="w-6 h-6 flex items-center justify-center bg-gray-200 rounded-md group">
<svg
className="w-4 h-4 text-gray-500 group-hover:text-orange-500"
fill="currentColor"
viewBox="0 0 20 20"
xmlns="http://www.w3.org/2000/svg"
>
<path
fillRule="evenodd"
d="M10 3a1 1 0 011 1v8.586l2.293-2.293a1 1 0 011.32-.083l.094.083a1 1 0 01.083 1.32l-.083.094-4 4a1 1 0 01-1.32.083l-.094-.083-4-4a1 1 0 011.32-1.497l.094.083L9 13.586V5a1 1 0 011-1z"
clipRule="evenodd"
/>
</svg>
</button>
</div>
{/* post image */}
<div className="flex-shrink-0">
<img
className="h-16 w-16 rounded-md"
src={post.data.thumbnail}
alt={post.data.title}
/>
</div>
{/* post content */}
<div>
{/* post title */}
<div className="flex-1">
<a
href={`https://www.reddit.com${post.data.permalink}`}
target="_blank"
rel="noreferrer"
className="block hover:text-orange-500 text-sm"
>
{post.data.title}
</a>
</div>
{/* post meta */}
<div className="flex items-center text-xs sm:text-sm text-gray-500">
<span className="whitespace-pre-wrap">
Posted by{' '}
<span className="font-medium">{post.data.author}</span>{' '}
{new Date(post.data.created * 1000).toLocaleDateString()}
</span>
</div>
</div>
</article>
));
})
) : (
<div>Loading...</div>
)}

<div ref={bottomOfPage} className="h-10" />

{isFetchingNextPage && <div>Loading...</div>}
</div>
</>
);
}
23 changes: 23 additions & 0 deletions src/feature/infinite-query/meta.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { ExampleProps } from 'utils/ExamplePage';

export const meta: ExampleProps = {
title: 'Infinite Query',
href: '/infinite-query',
// This is only enabled on the client as it will cause hydration error otherwise
// The problem is that RSC won't send the right header whilst the client will, leading to inconsistent behavior
clientOnly: true,
summary: (
<>
<p>Paginated queries with tRPC</p>
</>
),
detail: (
<>
<p>Using tRPC &amp; paginated queries.</p>
</>
),
files: [
{ title: 'Page', path: 'feature/infinite-query/index.tsx' },
{ title: 'Router', path: 'feature/infinite-query/router.tsx' },
],
};
57 changes: 57 additions & 0 deletions src/feature/infinite-query/router.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { t } from 'server/trpc/trpc';
import { z } from 'zod';

export type Items = {
items: {
data: {
children: {
data: {
id: string;
title: string;
selftext: string;
thumbnail: string;
score: number;
permalink: string;
created: number;
author: string;
};
}[];
};
};
nextCursor?: string;
};

export const infiniteQueryRouter = t.router({
getItems: t.procedure
.input(
z.object({
limit: z.number().min(1).max(100),
cursor: z.string().optional(),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The cursor should be validated so you can't inject anything into the url

}),
)
.query(async ({ input }) => {
const { cursor, limit } = input;
// set cursor to the previously returned nextCursor, or an empty string
let currentCursor = cursor || '';
// fetch data from API
do {
const items = await fetch(
`https://www.reddit.com/r/Aww/top.json?limit=${limit}?after=${currentCursor}`,
).then((res) => res.json());

// Set the cursor to the 'after' value from the response if it exists, which is the cursor for the next page
if (items.data.after) {
currentCursor = items.data.after;
} else {
// If there is no 'after' value, we've reached the end of the list
currentCursor = '';
}

// Return the items and the cursor for the next page
return {
items,
nextCursor: currentCursor,
} as Items;
} while (currentCursor !== '' || currentCursor !== undefined);
}),
});
8 changes: 7 additions & 1 deletion src/pages/index.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
import { meta as infiniteQueryMeta } from 'feature/infinite-query/meta';
import { meta as nextAuthMeta } from 'feature/next-auth/meta';
import { meta as reactHookFormMeta } from 'feature/react-hook-form/meta';
import { meta as ssgMeta } from 'feature/ssg/meta';
import Head from 'next/head';
import Link from 'next/link';
import { ExampleProps } from 'utils/ExamplePage';

const propsList: ExampleProps[] = [reactHookFormMeta, ssgMeta, nextAuthMeta];
const propsList: ExampleProps[] = [
reactHookFormMeta,
ssgMeta,
nextAuthMeta,
infiniteQueryMeta,
];

export default function Page() {
return (
Expand Down
13 changes: 13 additions & 0 deletions src/pages/infinite-query.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import FeaturePage from 'feature/infinite-query';
import { meta } from 'feature/infinite-query/meta';
import { ExamplePage } from 'utils/ExamplePage';

export default function Page() {
return (
<>
<ExamplePage {...meta}>
<FeaturePage />
</ExamplePage>
</>
);
}
2 changes: 2 additions & 0 deletions src/server/trpc/routers/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
/**
* This file contains the root router of your tRPC-backend
*/
import { infiniteQueryRouter } from 'feature/infinite-query/router';
import { authRouter } from 'feature/next-auth/router';
import { reactHookFormRouter } from 'feature/react-hook-form/router';
import ssgRouter from 'feature/ssg/router';
Expand All @@ -21,5 +22,6 @@ export const appRouter = t.router({
ssgRouter: ssgRouter,
authRouter: authRouter,
reactHookFormRouter: reactHookFormRouter,
infiniteQueryRouter: infiniteQueryRouter,
});
export type AppRouter = typeof appRouter;