[go: up one dir, main page]

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

Fixes #115 : Pagination is added via load more button #211

Merged
merged 15 commits into from
Oct 18, 2024

Conversation

madhav-relish
Copy link
Contributor
@madhav-relish madhav-relish commented Aug 13, 2024

Description

This PR fixes the pagination issue in mail

Changes

  • When the user clicks on load more button, the api call is made
  • While the api is fetching the data a loader is being displayed
  • User can perform any action and the refetch triggers to make sure data gets updated
  • After deleting or performing any action, the page doesn't resets to first page, the user stays where they were before

Note: Is there a better way of doing this? any suggestions?

email_pagination_fix.mp4

Related Issue

Fixes #115

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Introduced a "Load More" feature for email threads, allowing users to dynamically load additional emails.
    • Enhanced user interface with a loading spinner on the "Load More" button for better user feedback during the loading process.
    • Implemented infinite scrolling for email threads, improving navigation through large email lists.
  • Bug Fixes

    • Improved state management to ensure the latest email threads are displayed correctly based on user interactions.

Copy link
vercel bot commented Aug 13, 2024

@madhav-relish is attempting to deploy a commit to the Inbox Zero Team on Vercel.

A member of the Team first needs to authorize it.

Copy link
Contributor
coderabbitai bot commented Aug 13, 2024

Walkthrough

The recent updates enhance the Mail and EmailList components by transitioning to useSWRInfinite for data fetching, enabling pagination of email threads. A "Load More" functionality is introduced, allowing users to load additional threads seamlessly. The implementation includes new state management for loading and rendering, ensuring a responsive user experience as users navigate through their emails.

Changes

File Path Change Summary
apps/web/app/(app)/mail/page.tsx Updated data fetching logic to use useSWRInfinite for pagination, added loading state management, and adjusted rendering logic.
apps/web/components/email-list/EmailList.tsx Enhanced EmailList to support loading more threads with new props and a dynamic "Load More" button.

Assessment against linked issues

Objective Addressed Explanation
Add pagination to mail (##115)

Poem

🐇 In the meadow where emails flow,
A button gleams, a joyful show.
"Load More" whispers, threads appear,
A dance of messages, bring them near!
With every click, a story spins,
In this rabbit's world, the fun begins! ✨📧


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor
@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 4

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 23504a2 and fc067d7.

Files selected for processing (2)
  • apps/web/app/(app)/mail/page.tsx (3 hunks)
  • apps/web/components/email-list/EmailList.tsx (4 hunks)
Additional context used
Biome
apps/web/app/(app)/mail/page.tsx

[error] 91-91: Unexpected any. Specify a different type.

any disables many type checking rules. Its use should be avoided.

(lint/suspicious/noExplicitAny)


[error] 117-117: Unnecessary use of boolean literals in conditional expression.

Simplify your code by directly assigning the result without using a ternary operator.
If your goal is negation, you may use the logical NOT (!) or double NOT (!!) operator for clearer and concise code.
Check for more details about NOT operator.
Unsafe fix: Remove the conditional expression with

(lint/complexity/noUselessTernary)

apps/web/components/email-list/EmailList.tsx

[error] 45-45: Don't use '{}' as a type.

Prefer explicitly define the object shape. '{}' means "any non-nullable value".

(lint/complexity/noBannedTypes)


[error] 173-173: Don't use '{}' as a type.

Prefer explicitly define the object shape. '{}' means "any non-nullable value".

(lint/complexity/noBannedTypes)

Additional comments not posted (5)
apps/web/app/(app)/mail/page.tsx (3)

3-3: Imports look good.

The new imports for useCallback, useEffect, useState, and useSWR are appropriate for managing state and data fetching.


31-34: State management enhancements are appropriate.

The new state variables allThreads, nextPageTokenId, and isLoadMoreLoading are well-suited for implementing the "load more" feature.


76-81: useEffect implementation is effective.

The useEffect hook correctly updates the state variables when data changes, ensuring the component reflects the latest email threads and pagination token.

apps/web/components/email-list/EmailList.tsx (2)

36-37: Imports are appropriate.

The new imports for Button and ButtonLoader are necessary for implementing the "load more" button functionality.


495-513: Rendering logic for Load More button is effective.

The conditional rendering and loading feedback for the "Load More" button are well-implemented, enhancing user interaction.

Comment on lines 112 to 119
{allThreads && (
<List
emails={data.threads}
emails={allThreads}
refetch={refetch}
type={searchParams.type}
isLoadMore={nextPageTokenId ? true : false} // If nextPageToken doesn't exist then the button will be hidden
handleLoadMoreThreads={handleLoadMoreThreads}
isLoadMoreLoading={isLoadMoreLoading}
Copy link
Contributor

Choose a reason for hiding this comment

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

Simplify the conditional expression for isLoadMore.

The ternary operator is unnecessary here. You can directly use the truthy value of nextPageTokenId.

- isLoadMore={nextPageTokenId ? true : false}
+ isLoadMore={!!nextPageTokenId}
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
{allThreads && (
<List
emails={data.threads}
emails={allThreads}
refetch={refetch}
type={searchParams.type}
isLoadMore={nextPageTokenId ? true : false} // If nextPageToken doesn't exist then the button will be hidden
handleLoadMoreThreads={handleLoadMoreThreads}
isLoadMoreLoading={isLoadMoreLoading}
{allThreads && (
<List
emails={allThreads}
refetch={refetch}
type={searchParams.type}
isLoadMore={!!nextPageTokenId} // If nextPageToken doesn't exist then the button will be hidden
handleLoadMoreThreads={handleLoadMoreThreads}
isLoadMoreLoading={isLoadMoreLoading}
Tools
Biome

[error] 117-117: Unnecessary use of boolean literals in conditional expression.

Simplify your code by directly assigning the result without using a ternary operator.
If your goal is negation, you may use the logical NOT (!) or double NOT (!!) operator for clearer and concise code.
Check for more details about NOT operator.
Unsafe fix: Remove the conditional expression with

(lint/complexity/noUselessTernary)

Comment on lines 84 to 104
const handleLoadMoreThreads = async () => {
if (!nextPageTokenId) return;
setIsLoadMoreLoading(true);
mutate(
async (currentData) => {
const res = await fetch(
`/api/google/threads?nextPageToken=${nextPageTokenId}&${new URLSearchParams(
query as any,
).toString()}`,
);
const newData: ThreadsResponse = await res.json();

// update the threads and nextPageToken
return {
threads: [...(currentData?.threads || []), ...newData.threads],
nextPageToken: newData.nextPageToken,
};
},
{ revalidate: false },
).finally(() => setIsLoadMoreLoading(false));
};
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider refining the any type usage.

The handleLoadMoreThreads function is well-implemented for fetching additional threads. However, using any for query type should be avoided for better type safety.

- new URLSearchParams(query as any).toString()
+ new URLSearchParams(query as Record<string, string>).toString()
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const handleLoadMoreThreads = async () => {
if (!nextPageTokenId) return;
setIsLoadMoreLoading(true);
mutate(
async (currentData) => {
const res = await fetch(
`/api/google/threads?nextPageToken=${nextPageTokenId}&${new URLSearchParams(
query as any,
).toString()}`,
);
const newData: ThreadsResponse = await res.json();
// update the threads and nextPageToken
return {
threads: [...(currentData?.threads || []), ...newData.threads],
nextPageToken: newData.nextPageToken,
};
},
{ revalidate: false },
).finally(() => setIsLoadMoreLoading(false));
};
const handleLoadMoreThreads = async () => {
if (!nextPageTokenId) return;
setIsLoadMoreLoading(true);
mutate(
async (currentData) => {
const res = await fetch(
`/api/google/threads?nextPageToken=${nextPageTokenId}&${new URLSearchParams(
query as Record<string, string>,
).toString()}`,
);
const newData: ThreadsResponse = await res.json();
// update the threads and nextPageToken
return {
threads: [...(currentData?.threads || []), ...newData.threads],
nextPageToken: newData.nextPageToken,
};
},
{ revalidate: false },
).finally(() => setIsLoadMoreLoading(false));
};
Tools
Biome

[error] 91-91: Unexpected any. Specify a different type.

any disables many type checking rules. Its use should be avoided.

(lint/suspicious/noExplicitAny)

Comment on lines 171 to 173
isLoadMore?: boolean;
isLoadMoreLoading?: boolean;
handleLoadMoreThreads?: () => {};
Copy link
Contributor

Choose a reason for hiding this comment

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

Refine the type for handleLoadMoreThreads.

Avoid using {} as a type. Specify a more precise type for handleLoadMoreThreads.

- handleLoadMoreThreads?: () => {};
+ handleLoadMoreThreads?: () => void;
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
isLoadMore?: boolean;
isLoadMoreLoading?: boolean;
handleLoadMoreThreads?: () => {};
isLoadMore?: boolean;
isLoadMoreLoading?: boolean;
handleLoadMoreThreads?: () => void;
Tools
Biome

[error] 173-173: Don't use '{}' as a type.

Prefer explicitly define the object shape. '{}' means "any non-nullable value".

(lint/complexity/noBannedTypes)

Comment on lines 43 to 45
isLoadMore?: boolean;
isLoadMoreLoading?: boolean;
handleLoadMoreThreads?: () => {};
Copy link
Contributor

Choose a reason for hiding this comment

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

Refine the type for handleLoadMoreThreads.

Avoid using {} as a type. Specify a more precise type for handleLoadMoreThreads.

- handleLoadMoreThreads?: () => {};
+ handleLoadMoreThreads?: () => void;
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
isLoadMore?: boolean;
isLoadMoreLoading?: boolean;
handleLoadMoreThreads?: () => {};
isLoadMore?: boolean;
isLoadMoreLoading?: boolean;
handleLoadMoreThreads?: () => void;
Tools
Biome

[error] 45-45: Don't use '{}' as a type.

Prefer explicitly define the object shape. '{}' means "any non-nullable value".

(lint/complexity/noBannedTypes)

Copy link
Contributor
@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between fc067d7 and e70e5c2.

Files selected for processing (2)
  • apps/web/app/(app)/mail/page.tsx (3 hunks)
  • apps/web/components/email-list/EmailList.tsx (4 hunks)
Files skipped from review as they are similar to previous changes (2)
  • apps/web/app/(app)/mail/page.tsx
  • apps/web/components/email-list/EmailList.tsx

apps/web/app/(app)/mail/page.tsx Outdated Show resolved Hide resolved
apps/web/app/(app)/mail/page.tsx Outdated Show resolved Hide resolved
apps/web/components/email-list/EmailList.tsx Outdated Show resolved Hide resolved
apps/web/components/email-list/EmailList.tsx Outdated Show resolved Hide resolved
apps/web/components/email-list/EmailList.tsx Outdated Show resolved Hide resolved
apps/web/components/email-list/EmailList.tsx Outdated Show resolved Hide resolved
- changed the refetch logic
- Replaced useSwr with useSWRInfinite for pagination
- Changed the variable names
- All the features, delete, archieve, bulk delete etc works fine now
- On performing any action the page doesn't move back to the 1st page
- On delete now refetch happens properly
Copy link
Contributor
@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between e70e5c2 and df5f0f3.

Files selected for processing (3)
  • apps/web/app/(app)/mail/page.tsx (2 hunks)
  • apps/web/components/ActionButtons.tsx (2 hunks)
  • apps/web/components/email-list/EmailList.tsx (4 hunks)
Additional context used
Biome
apps/web/app/(app)/mail/page.tsx

[error] 30-30: Unexpected any. Specify a different type.

any disables many type checking rules. Its use should be avoided.

(lint/suspicious/noExplicitAny)


[error] 32-32: Unexpected any. Specify a different type.

any disables many type checking rules. Its use should be avoided.

(lint/suspicious/noExplicitAny)

Additional comments not posted (10)
apps/web/components/ActionButtons.tsx (2)

23-23: LGTM!

The updated refetch function signature, which now accepts an optional threadId parameter, aligns well with the PR objectives of implementing pagination functionality. This change enhances the flexibility of the refetch function by allowing it to potentially target a specific thread when fetching additional data.


51-51: LGTM!

Updating the onTrash callback implementation to pass the threadId to the refetch function is a good change. It ensures that the refetch operation is contextually aware of which thread is being referenced, making it more precise and relevant to the current action being performed. This change aligns well with the PR objectives of implementing pagination functionality.

apps/web/app/(app)/mail/page.tsx (6)

4-4: LGTM!

The import statement for useSWRInfinite is correct and necessary for implementing the pagination feature.


35-40: LGTM!

The usage of useSWRInfinite with the getKey function and the provided options is correct and necessary for implementing the pagination feature.


42-45: LGTM!

The logic for defining allThreads, isLoadingMore, and showLoadMore is correct and necessary for rendering the email threads and handling the loading state.


47-70: LGTM!

The implementation of the refetch function for refreshing the email list upon archive is correct and necessary. The optimistic update of the cached data by filtering out removed thread IDs is a good approach. The usage of the mutate function with a simpler structure improves clarity and efficiency.


79-81: LGTM!

The implementation of the handleLoadMore function for incrementing the size state by 1 is correct and necessary for loading more email threads when the "load more" button is clicked.


88-96: LGTM!

The usage of the LoadingContent component for handling the loading and error states is correct. The rendering of the List component with the flattened array of all threads and additional props for pagination is also correct and necessary for displaying the email threads.

apps/web/components/email-list/EmailList.tsx (2)

36-49: LGTM!

The changes to the List function look good. The new props are correctly added to support the load more feature, and the destructuring is updated accordingly. The prop names are descriptive and follow the naming conventions.


Line range hint 167-512: LGTM!

The changes to the EmailList function look good. The new props are correctly added to support the load more feature, and the destructuring is updated accordingly. The prop names are descriptive and follow the naming conventions.

The load more button is correctly implemented with the following observations:

  • The button is conditionally rendered based on the showLoadMore prop.
  • The button is disabled when the isLoadingMore prop is true.
  • The button displays a loading indicator when the isLoadingMore prop is true.
  • The button text is clear and concise.
  • The button styling is consistent with the rest of the UI.

Great work on implementing the load more feature!

apps/web/app/(app)/mail/page.tsx Outdated Show resolved Hide resolved
Comment on lines 49 to 62
const refetch = useCallback(
(removedThreadIds?: string[]) => {
mutate(undefined, {
rollbackOnError: true,
optimisticData: (currentData) => {
if (!removedThreadIds)
return {
threads: currentData?.threads || [],
nextPageToken: undefined,
};
const threads =
currentData?.threads.filter(
mutate(
(currentData) => {
if (!currentData) return currentData;
if (!removedThreadIds) return currentData;

return currentData.map((page) => ({
...page,
threads: page.threads.filter(
(t) => !removedThreadIds.includes(t.id),
) || [];
return { threads, nextPageToken: undefined };
),
}));
},
Copy link
Owner

Choose a reason for hiding this comment

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

Hey, I realise this was messy code before. But what's the reason the optimistic update was removed?

Copy link
Owner

Choose a reason for hiding this comment

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

But also if it works from your video, then maybe it's fine.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Just for the simplicity of the logic and code.

const setRefetchEmailList = useSetAtom(refetchEmailListAtom);
useEffect(() => {
setRefetchEmailList({ refetch });
}, [refetch, setRefetchEmailList]);

const handleLoadMore = () => {
Copy link
Owner

Choose a reason for hiding this comment

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

Minor, but you can do useCallback here.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Done!

@@ -472,6 +488,28 @@ export function EmailList(props: {
/>
);
})}
{/* Load more button to fetch more data */}
Copy link
Owner

Choose a reason for hiding this comment

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

can drop this comment

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Dropped.

@@ -472,6 +488,28 @@ export function EmailList(props: {
/>
);
})}
{/* Load more button to fetch more data */}
{showLoadMore && (
<div className="pb-2">
Copy link
Owner

Choose a reason for hiding this comment

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

styling for this button is off in your video. adding px-4 may fix this. you could also drop the wrapper div, and just do mb-2 mx-4 on the button

Copy link
Contributor Author
@madhav-relish madhav-relish Sep 29, 2024

Choose a reason for hiding this comment

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

Removed the wrapper div and added mb-2 for the button, mx-4 was creating overflow

<div className="pb-2">
<Button
variant="outline"
className="w-full py-4"
Copy link
Owner

Choose a reason for hiding this comment

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

is py-4 needed? there's button size prop if you want to adjust sizing but not sure that's needed here

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Added size prop and removed py-4

Comment on lines 27 to 33
if (previousPageData && !previousPageData.nextPageToken) return null;
// For the first page, use the base query
if (pageIndex === 0)
return `/api/google/threads?${new URLSearchParams(query as Record<string, string>).toString()}`;
// For subsequent pages, append the nextPageToken
return `/api/google/threads?nextPageToken=${previousPageData?.nextPageToken}&${new URLSearchParams(query as any).toString()}`;
};
Copy link
Owner

Choose a reason for hiding this comment

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

cleaner way to do this is without the if/else around the whole row as most of it is duplicated.

something like this:

const getKey = (pageIndex: number, previousPageData: ThreadsResponse | null) => {
  if (previousPageData && !previousPageData.nextPageToken) return null;

  const queryParams = new URLSearchParams(query as Record<string, string>);
  
  if (previousPageData?.nextPageToken) {
    queryParams.set('nextPageToken', previousPageData.nextPageToken);
  }

  return `/api/google/threads?${queryParams.toString()}`;
};

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Done!

Copy link
Contributor
@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (4)
apps/web/components/email-list/EmailList.tsx (3)

44-46: LGTM: New props for "Load More" functionality.

The new props (showLoadMore, isLoadingMore, and handleLoadMore) are correctly added and align with the PR objectives. They provide the necessary controls for implementing the "Load More" feature.

Consider grouping these related props into a single object for better maintainability:

- showLoadMore?: boolean;
- isLoadingMore?: boolean;
- handleLoadMore?: () => void;
+ loadMore?: {
+   show: boolean;
+   isLoading: boolean;
+   handle: () => void;
+ };

This change would make it easier to add or modify load more related props in the future.


167-169: LGTM: Consistent prop additions to EmailList component.

The new props for the "Load More" functionality are correctly added to the EmailList component, maintaining consistency with the List component.

For consistency with the suggested change in the List component, consider grouping these related props:

- showLoadMore?: boolean;
- isLoadingMore?: boolean;
- handleLoadMore?: () => void;
+ loadMore?: {
+   show: boolean;
+   isLoading: boolean;
+   handle: () => void;
+ };

This change would improve maintainability and keep the components consistent.


491-512: LGTM: Well-implemented "Load More" button.

The "Load More" button is correctly implemented with appropriate conditional rendering, loading state handling, and user feedback. This aligns well with the PR objectives.

Consider adding an aria-label to the button for improved accessibility:

 <Button
   variant="outline"
   className="mb-2 w-full"
   size={"sm"}
   
   disabled={isLoadingMore}
+  aria-label="Load more emails"
 >
   {/* ... */}
 </Button>

This change would provide better context for screen reader users.

apps/web/app/(app)/mail/page.tsx (1)

49-50: Address the TODO comment regarding refetch function

There's a TODO comment questioning if storing refetch in the atom is the best approach. If you'd like assistance exploring alternative solutions or improving this implementation, I can help.

Would you like me to suggest alternative methods or open a new GitHub issue to track this task?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between c670a61 and d980582.

📒 Files selected for processing (2)
  • apps/web/app/(app)/mail/page.tsx (2 hunks)
  • apps/web/components/email-list/EmailList.tsx (4 hunks)
🧰 Additional context used
🪛 Biome
apps/web/app/(app)/mail/page.tsx

[error] 80-80: This hook does not specify all of its dependencies: setSize

This dependency is not specified in the hook dependency list.

Either include it or remove the dependency array

(lint/correctness/useExhaustiveDependencies)

🔇 Additional comments (4)
apps/web/components/email-list/EmailList.tsx (3)

36-38: LGTM: New imports for "Load More" functionality.

The new imports (Button, ChevronsDownIcon, and ButtonLoader) are correctly added and necessary for implementing the "Load More" feature.


48-49: LGTM: Correct usage and propagation of new props.

The new props are correctly destructured and passed down to the EmailList component, ensuring proper propagation of the "Load More" functionality.

Also applies to: 116-118


Line range hint 1-562: Overall: Excellent implementation of the "Load More" functionality.

The changes in this file successfully implement the pagination feature via a "Load More" button, as described in the PR objectives. The code is well-structured, consistent, and aligns with the existing codebase. The new functionality is properly integrated into both the List and EmailList components.

A few minor suggestions were made to further improve the code:

  1. Grouping the new props into a single object for better maintainability.
  2. Adding an aria-label to the "Load More" button for improved accessibility.

These suggestions are optional and do not detract from the overall quality of the implementation. Great job on this feature!

apps/web/app/(app)/mail/page.tsx (1)

23-34: Duplicate Comment: Consider wrapping getKey function with useCallback

The suggestion to wrap the getKey function with useCallback to memoize it and prevent unnecessary re-renders is still valid.

apps/web/app/(app)/mail/page.tsx Outdated Show resolved Hide resolved
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@madhav-relish
Copy link
Contributor Author

@elie222 Any more changes required here?

Copy link
Contributor
@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (2)
apps/web/components/email-list/EmailList.tsx (1)

166-181: LGTM: "Load More" functionality implemented correctly.

The EmailList component has been updated with new props and a "Load More" button, implementing the pagination feature as requested. The button is conditionally rendered and properly manages loading state.

Consider adding an aria-label to the "Load More" button for improved accessibility:

 <Button
   variant="outline"
   className="mb-2 w-full"
   size={"sm"}
   
   disabled={isLoadingMore}
+  aria-label="Load more emails"
 >
   {/* ... */}
 </Button>

Also applies to: 495-516

apps/web/app/(app)/mail/page.tsx (1)

49-52: Address the TODO: Evaluate the approach for storing refetch in the atom

The TODO comment indicates uncertainty about using an atom to store the refetch function. Storing functions in atoms can lead to potential issues such as unnecessary re-renders or stale closures.

Consider alternative approaches:

  • Use Context API: Utilize React's Context API to provide the refetch function to components that require it without prop drilling.
  • Custom Hook: Create a custom hook that encapsulates the refetch logic, allowing components to access it as needed.
  • Event Emitter: Implement an event emitter or a Pub/Sub pattern to trigger refetch operations across components.

Would you like assistance in refactoring this implementation to enhance maintainability and adhere to best practices?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 14c1d0b and 64cd66a.

📒 Files selected for processing (2)
  • apps/web/app/(app)/mail/page.tsx (2 hunks)
  • apps/web/components/email-list/EmailList.tsx (7 hunks)
🧰 Additional context used
🔇 Additional comments (4)
apps/web/components/email-list/EmailList.tsx (4)

36-38: LGTM: New imports for "Load More" functionality.

The added imports for Button, ChevronsDownIcon, and ButtonLoader are appropriate for implementing the new "Load More" feature.


40-53: LGTM: New props for "Load More" functionality.

The List component has been updated with new props (showLoadMore, isLoadingMore, handleLoadMore) to support the "Load More" feature. These props are correctly passed down to the EmailList component.


542-545: LGTM: Improved prop handling in ResizeGroup.

The ResizeGroup component has been refactored to use object destructuring for its props, which enhances code readability and follows modern JavaScript best practices.


Line range hint 1-566: Overall: Excellent implementation of pagination via "Load More" functionality.

The changes in this file successfully implement the pagination feature using a "Load More" button, addressing the objectives outlined in the PR. The implementation allows users to incrementally load more emails, improving the performance and user experience of the mail interface. The code is well-structured, and the new functionality is seamlessly integrated into the existing components.

A few key points:

  1. New props are correctly added and passed down through components.
  2. The "Load More" button is implemented with proper conditional rendering and state management.
  3. The ResizeGroup component has been refactored for improved readability.

Great job on this implementation!

@elie222
Copy link
Owner
elie222 commented Oct 18, 2024

Seems to be working great on the Mail page. Wondering if we can also get it to work on the view when a user views emails on other pages. eg bulk unsubscribe page doesn't show load more:
CleanShot 2024-10-17 at 23 09 03@2x

Probably need to extract this into its own hook:

  const query: ThreadsQuery = searchParams.type
    ? { type: searchParams.type }
    : {};

  const getKey = (
    pageIndex: number,
    previousPageData: ThreadsResponse | null,
  ) => {
    if (previousPageData && !previousPageData.nextPageToken) return null;
    const queryParams = new URLSearchParams(query as Record<string, string>);
    // Append nextPageToken for subsequent pages
    if (pageIndex > 0 && previousPageData?.nextPageToken) {
      queryParams.set("nextPageToken", previousPageData.nextPageToken);
    }
    return `/api/google/threads?${queryParams.toString()}`;
  };

  const { data, size, setSize, isLoading, error, mutate } =
    useSWRInfinite<ThreadsResponse>(getKey, {
      keepPreviousData: true,
      dedupingInterval: 1_000,
      revalidateOnFocus: false,
    });

  const allThreads = data ? data.flatMap((page) => page.threads) : [];
  const isLoadingMore =
    isLoading || (size > 0 && data && typeof data[size - 1] === "undefined");
  const showLoadMore = data ? !!data[data.length - 1]?.nextPageToken : false;

e.g. for usage in apps/web/app/(app)/stats/NewsletterModal.tsx

@elie222 elie222 merged commit be21388 into elie222:main Oct 18, 2024
1 of 2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Mail: Pagination
2 participants