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

fix: Add unsubscribe functionality to NewsletterModal #210

Open
wants to merge 7 commits into
base: main
Choose a base branch
from

Conversation

aryanprince
Copy link

@aryanprince aryanprince commented Aug 11, 2024

Summary

This PR fixes a bug where unsubscribing from a newsletter via the newsletter modal failed to work as expected. Specifically, the bug prevented the decrement of unsubscribe credits, updating of the newsletter status, triggering of analytics and more. You can find more details about the issue here.

The main issue was that the unsubscribe buttons in the app were performing different actions. With this fix, both unsubscribe buttons (table row action and the one in the newsletter modal) now use the same useUnsubscribeButton hook, ensuring consistent behavior across the app.

Fixes #209

Changes

  • Updated the onClick property for the unsubscribe button within the newsletter modal to use the onUnsubscribe function from the useUnsubscribeButton hook, ensuring all expected actions are executed.
  • Passed the mutate prop from the parent BulkUnsubscribeSection component to the NewsletterModal component.
  • Refactored all instances of the NewsletterModal component cus changes in its props, which are now required (was optional before).

Demo

Before the fix

The GIF below shows the unsubscribe process using the table row action button, which works as expected:

Error - Unsubbing using direct unsub button

In contrast, the GIF below demonstrates unsubscribing via the newsletter modal, which does not work as expected. It doesn't update the unsubscribe count or update the newsletter's status:

Error - Unsubbing using email dialog menu

After the fix

The GIF below illustrates the corrected behavior after applying this PR. Unsubscribing via the newsletter modal now does all of the same actions as clicking the unsubscribe button from the table row action button:

Fixed - Unsubbing using email dialog menu

Summary by CodeRabbit

  • New Features

    • Introduced conditional rendering for the NewsletterModal across multiple components to enhance performance and user experience.
    • Added a required newsletter prop and an optional mutate prop to the NewsletterModal, improving data handling and interactivity.
    • Enhanced the unsubscribe button with a dynamic loading state for better user feedback during the unsubscribe process.
    • Integrated new hooks for managing subscription access and the unsubscribe process in the NewsletterModal.
  • Bug Fixes

    • Improved clarity and efficiency by eliminating unnecessary renders of the NewsletterModal when conditions are not met.
  • Style

    • Minor formatting adjustments in the ColorSelector and LinkSelector components for improved consistency.

- Pass the `mutate` prop from parent component to the `NewsletterModal` component
- Uses the `useUnsubscribeButton` hook to manage the newsletter unsubscription
- On clicking the unsubscribe button from the modal, calls the `onUnsubscribe` function from the `useUnsubscribeButton` hook

Fixes elie222#209
- Updates `NewsletterModal` component's usage throughout application as one of its props is no longer optional
Copy link

vercel bot commented Aug 11, 2024

@aryanprince is attempting to deploy a commit to the Inbox Zero Team on Vercel.

A member of the Team first needs to authorize it.

@CLAassistant
Copy link

CLAassistant commented Aug 11, 2024

CLA assistant check
All committers have signed the CLA.

@aryanprince aryanprince changed the title fix: Add unsubscribe functionality to NewsletterModal (#209) fix: Add unsubscribe functionality to NewsletterModal Aug 11, 2024
Copy link
Contributor

coderabbitai bot commented Aug 11, 2024

Walkthrough

The recent changes enhance the rendering logic of the NewsletterModal across various components by implementing conditional rendering based on state values. This ensures the modal is displayed only when relevant, improving performance and user experience. Additionally, the NewsletterModal now requires a newsletter prop, and a new mutate function prop allows for state updates upon user actions, addressing a critical bug related to unsubscribe functionalities.

Changes

Files Change Summary
apps/web/app/(app)/bulk-unsubscribe/BulkUnsubscribeSection.tsx Added conditional rendering for NewsletterModal based on openedNewsletter. Introduced a new mutate prop.
apps/web/app/(app)/cold-email-blocker/ColdEmailList.tsx Implemented conditional rendering for NewsletterModal based on openedRow.
apps/web/app/(app)/cold-email-blocker/ColdEmailRejected.tsx Modified rendering logic to conditionally display NewsletterModal when openedRow is truthy.
apps/web/app/(app)/new-senders/NewSenders.tsx Updated NewsletterModal rendering to be conditional on openedNewsletter.
apps/web/app/(app)/stats/NewsletterModal.tsx Changed newsletter prop to required and added optional mutate prop. Enhanced unsubscribe logic with new hooks.
apps/web/app/(app)/compose/selectors/color-selector.tsx Minor formatting change in className property of PopoverContent.
apps/web/app/(app)/compose/selectors/link-selector.tsx Minor formatting change in className of a div element.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant NewsletterModal
    participant AppState

    User->>AppState: Open NewsletterModal
    AppState->>NewsletterModal: Check opened state
    alt If opened state is true
        AppState->>NewsletterModal: Render modal
        User->>NewsletterModal: Click unsubscribe
        NewsletterModal->>AppState: Trigger unsubscribe action
        AppState->>NewsletterModal: Update state and credits
    else If opened state is false
        AppState->>NewsletterModal: Do not render modal
    end
Loading

Assessment against linked issues

Objective Addressed Explanation
Unsubscribe credits not decrementing when using the newsletter modal button (#[209])
Ensure modal only shows relevant information and actions (#[209])

🐰✨ In the code with a hop and a skip,
The modal’s now clever, oh what a trip!
Only when needed, it opens with grace,
Unsubscribing with ease, a smile on your face!
Hooray for the changes, let’s dance and rejoice,
With each little fix, we’re lifting our voice! 🎉✨


Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between ae22a6c and 17ce178.

Files selected for processing (1)
  • apps/web/app/(app)/new-senders/NewSenders.tsx (3 hunks)
Files skipped from review as they are similar to previous changes (1)
  • apps/web/app/(app)/new-senders/NewSenders.tsx

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: 1

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

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

Files selected for processing (5)
  • apps/web/app/(app)/bulk-unsubscribe/BulkUnsubscribeSection.tsx (1 hunks)
  • apps/web/app/(app)/cold-email-blocker/ColdEmailList.tsx (1 hunks)
  • apps/web/app/(app)/cold-email-blocker/ColdEmailRejected.tsx (1 hunks)
  • apps/web/app/(app)/new-senders/NewSenders.tsx (1 hunks)
  • apps/web/app/(app)/stats/NewsletterModal.tsx (2 hunks)
Additional context used
Biome
apps/web/app/(app)/stats/NewsletterModal.tsx

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

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

(lint/suspicious/noExplicitAny)


[error] 33-34: All these imports are only used as types.

Importing the types with import type ensures that they are removed by the transpilers and avoids loading unnecessary modules.
Safe fix: Use import type.

(lint/style/useImportType)

Additional comments not posted (7)
apps/web/app/(app)/cold-email-blocker/ColdEmailRejected.tsx (1)

68-73: Conditional Rendering of NewsletterModal

The conditional rendering of NewsletterModal based on openedRow is a good practice. It prevents unnecessary rendering of the modal when there is no relevant data to display, enhancing performance and user experience.

apps/web/app/(app)/bulk-unsubscribe/BulkUnsubscribeSection.tsx (1)

226-233: Conditional Rendering and New mutate Prop

The conditional rendering of NewsletterModal based on openedNewsletter enhances performance by rendering the modal only when necessary. The introduction of the mutate prop allows for state updates, improving the component's functionality.

apps/web/app/(app)/stats/NewsletterModal.tsx (3)

39-42: Required newsletter Prop and Optional mutate Prop

The change to make the newsletter prop required ensures that the component always receives necessary data, enhancing robustness. The optional mutate prop allows for flexible state handling, which is a valuable addition.

Tools
Biome

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

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

(lint/suspicious/noExplicitAny)


45-45: Default Value for mutate

Providing a default value for mutate ensures that the component can function even if the prop is not explicitly passed, which is a good practice for maintaining component stability.


56-62: Integration of useUnsubscribeButton Hook

The integration of the useUnsubscribeButton hook centralizes the unsubscribe logic, improving maintainability and ensuring consistent behavior across different parts of the application.

apps/web/app/(app)/cold-email-blocker/ColdEmailList.tsx (1)

146-151: Conditional rendering of NewsletterModal improves performance.

The change ensures that the NewsletterModal is only rendered when openedRow is truthy, preventing unnecessary renders and enhancing performance.

apps/web/app/(app)/new-senders/NewSenders.tsx (1)

214-220: Conditional rendering of NewsletterModal enhances performance.

The change ensures that the NewsletterModal is only rendered when openedNewsletter is truthy, preventing unnecessary renders and improving performance.

onClose: (isOpen: boolean) => void;
refreshInterval?: number;
mutate?: () => Promise<any>;
Copy link
Contributor

@coderabbitai coderabbitai bot Aug 11, 2024

Choose a reason for hiding this comment

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

Avoid Using any Type

The use of any should be avoided to maintain type safety. Consider specifying a more precise type for the mutate function to enhance type checking.

- mutate?: () => Promise<any>;
+ mutate?: () => Promise<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
mutate?: () => Promise<any>;
mutate?: () => Promise<void>;
Tools
Biome

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

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

(lint/suspicious/noExplicitAny)

Copy link
Author

Choose a reason for hiding this comment

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

I agree bot. I tried my best to make the suggestion of mutate?: () => Promise<void>; work but there were a lot of side effects with it. Would be happy to see a fix for this.

The issue here is that the mutate function passed down to this NewsletterModal component is to mutate multiple newsletters, but this component only needs to mutate a single newsletter.

The only fixes I could think of was to:

  1. Create a new API route to mutate a single newsletter as well, along with the existing API route to mutate multiple newsletters.
  2. Update the useUnsubscribeButton hook's logic, and all of its usages.

I think this will need refactoring in the future regardless. Would be happy to have a look at this later.

Copy link
Contributor

Choose a reason for hiding this comment

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

@aryanprince, thanks for sharing your insights and potential solutions. It seems like a refactoring effort could indeed be beneficial to address the scope of the mutate function. To ensure this doesn't get lost, would you like me to create a follow-up issue to track this refactoring task? This way, we can revisit it when the time is right and ensure the NewsletterModal component handles mutations more precisely. Let me know how you'd like to proceed!

Comment on lines 81 to 87
{!unsubscribeLoading && <span>Unsubscribe</span>}
{!!unsubscribeLoading && (
<div className="flex cursor-not-allowed items-center opacity-50">
<ButtonLoader />
<span>Unsubscribing...</span>
</div>
)}
Copy link
Owner

Choose a reason for hiding this comment

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

Could use a ternary to make this cleaner. ie: unsubscribeLoading ? Unsub : Loading...

If you're trying to add disabled state, then you could add disabled={unsubscribeLoading} to the button itself.

Copy link
Author

Choose a reason for hiding this comment

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

Updated it now! Used a ternary here instead and added the disabled state to the button.

Copy link
Owner

@elie222 elie222 left a comment

Choose a reason for hiding this comment

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

2 comments

onClose={() => setOpenedNewsletter(undefined)}
refreshInterval={props.refreshInterval}
/>
{openedNewsletter && (
Copy link
Owner

Choose a reason for hiding this comment

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

Did you need to add {openedNewsletter && (?
I think it stops the animation when it's done like that. Or was this added to fix a bug?

Copy link
Author

Choose a reason for hiding this comment

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

Reason

This is cus the <NewsletterModal /> component now requires (non-optional) the openedNewsletter prop, which was previously optional.

The reason for this change is that the component now uses the existing useUnsubscribeButton hook, which does need a required openedNewsletter prop.

Initially, I tried keeping openedNewsletter as optional (to have less diffs like the one you brought up here), but that would have required introducing a second hook for unsubscribing, which would complicate the logic unnecessarily.

Minor Benefit

Additionally, making openedNewsletter a required prop also ensures that the <NewsletterModal /> is only rendered when all necessary data is present, making it more robust and predictable in terms of when it renders throughout the app.

Quick Demo

Also, below GIF shows that the animations are still intact. No issues with that according to my testing.

CleanShot 2024-08-23 at 12 29 31

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 2f53ad3 and 1b7c1b8.

Files selected for processing (1)
  • apps/web/app/(app)/stats/NewsletterModal.tsx (2 hunks)
Additional context used
Biome
apps/web/app/(app)/stats/NewsletterModal.tsx

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

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

(lint/suspicious/noExplicitAny)


[error] 4-5: All these imports are only used as types.

Importing the types with import type ensures that they are removed by the transpilers and avoids loading unnecessary modules.
Safe fix: Use import type.

(lint/style/useImportType)

Additional comments not posted (2)
apps/web/app/(app)/stats/NewsletterModal.tsx (2)

42-42: Avoid using any type for mutate prop.

The use of any should be avoided to maintain type safety. Consider specifying a more precise type for the mutate function to enhance type checking.

- mutate?: () => Promise<any>;
+ mutate?: () => Promise<void>;
Tools
Biome

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

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

(lint/suspicious/noExplicitAny)


74-90: Enhancement: Improved unsubscribe button logic.

The unsubscribe button now includes a loading state and is disabled during the unsubscribe action, enhancing user experience by preventing multiple submissions and providing feedback. The implementation is correct.

apps/web/app/(app)/stats/NewsletterModal.tsx Outdated Show resolved Hide resolved
>
Unsubscribe
{unsubscribeLoading ? (
// Button loading state
Copy link
Owner

Choose a reason for hiding this comment

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

really don't need this comment lol. pretty clear from the code that it's loading state 😆

Copy link
Author

Choose a reason for hiding this comment

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

Haha done, removed the comments now

<span>Unsubscribing...</span>
</div>
) : (
// Button default state
Copy link
Owner

Choose a reason for hiding this comment

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

yes lol. you can remove this comment

Copy link
Author

Choose a reason for hiding this comment

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

Removed this comment too

@elie222
Copy link
Owner

elie222 commented Sep 24, 2024

Hey, took a look again. I'm going to run myself locally and then will get it merged in after. I see there's also merge conflicts now :(

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 1b7c1b8 and 6ff6a65.

Files selected for processing (1)
  • apps/web/app/(app)/stats/NewsletterModal.tsx (2 hunks)
Additional context used
Learnings (1)
apps/web/app/(app)/stats/NewsletterModal.tsx (1)
Learnt from: aryanprince
PR: elie222/inbox-zero#210
File: apps/web/app/(app)/stats/NewsletterModal.tsx:2-4
Timestamp: 2024-08-23T11:37:26.779Z
Learning: `MoreDropdown` is a React component and `useUnsubscribeButton` is a custom React hook, and they should not be imported using `import type`.
Biome
apps/web/app/(app)/stats/NewsletterModal.tsx

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

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

(lint/suspicious/noExplicitAny)


[error] 4-5: All these imports are only used as types.

Importing the types with import type ensures that they are removed by the transpilers and avoids loading unnecessary modules.
Safe fix: Use import type.

(lint/style/useImportType)

Additional comments not posted (6)
apps/web/app/(app)/stats/NewsletterModal.tsx (6)

2-4: LGTM: Correct imports added

The new imports for MoreDropdown and useUnsubscribeButton are correctly added. These are not type-only imports, so the current import statement is appropriate.


12-24: LGTM: UI component imports added

The new imports for various UI components (AlertBasic, LoadingContent, usePremium, Tooltip, Button, ButtonLoader, Dialog, DialogContent, DialogHeader, DialogTitle) are correctly added. These imports are necessary for the new functionality in the NewsletterModal component.


27-36: LGTM: Utility and type imports added

The new imports for various utilities, types, and external libraries (onAutoArchive, getGmailFilterSettingsUrl, ZodPeriod, BarChart, ExternalLinkIcon, useSession, Link, usePostHog, DateRange, useSWR) are correctly added. These imports support the enhanced functionality of the NewsletterModal component.


45-62: LGTM: Enhanced functionality with new hooks

The changes in this section improve the NewsletterModal component:

  1. Setting a default value for mutate is a good practice, ensuring the function always exists.
  2. The introduction of usePremium and usePostHog hooks adds necessary functionality.
  3. The useUnsubscribeButton hook is correctly implemented with all required props.

These changes enhance the component's capabilities and maintain good coding practices.


74-89: LGTM: Improved unsubscribe button functionality

The changes to the unsubscribe button enhance its functionality and user experience:

  1. Disabling the button during the unsubscribe process prevents multiple clicks.
  2. Using onUnsubscribe from the hook ensures consistent behavior across the application.
  3. The ternary operator for the loading state improves code readability and provides clear feedback to the user.

These changes effectively address the issue mentioned in the PR objectives, ensuring that unsubscribing via the modal performs all necessary actions.


Line range hint 1-252: Summary: Effective solution to unsubscribe functionality issue

This PR successfully addresses the bug related to the unsubscribe functionality in the NewsletterModal component. The key improvements include:

  1. Consistent use of the useUnsubscribeButton hook for both unsubscribe methods.
  2. Proper handling of loading states and user feedback during the unsubscribe process.
  3. Enhanced type safety with required props and suggested improvements for the mutate prop type.

These changes ensure that unsubscribing via the newsletter modal now correctly decrements unsubscribe credits, updates the newsletter status, and triggers analytics, achieving consistency with the table row action buttons.

The code maintains good quality and readability. The only minor suggestion is to consider using a more specific type for the mutate prop instead of any.

Overall, this PR effectively resolves the issue described in #209 and improves the overall functionality of the NewsletterModal component.

Tools
Biome

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

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

(lint/suspicious/noExplicitAny)


[error] 4-5: All these imports are only used as types.

Importing the types with import type ensures that they are removed by the transpilers and avoids loading unnecessary modules.
Safe fix: Use import type.

(lint/style/useImportType)

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: 3

Outside diff range and nitpick comments (3)
apps/web/app/(app)/cold-email-blocker/ColdEmailRejected.tsx (1)

68-73: Improved rendering logic, but consider simplifying the newsletter prop.

The conditional rendering of the NewsletterModal is a good improvement. It enhances performance by avoiding unnecessary renders when openedRow is undefined.

However, the newsletter prop assignment can be simplified:

Consider simplifying the newsletter prop assignment:

 {openedRow && (
   <NewsletterModal
-    newsletter={openedRow && { name: openedRow.fromEmail || "" }}
+    newsletter={{ name: openedRow.fromEmail || "" }}
     onClose={() => setOpenedRow(undefined)}
   />
 )}

This change removes the redundant check for openedRow, as it's already guaranteed to be truthy within this block.

apps/web/app/(app)/stats/NewsletterModal.tsx (1)

Line range hint 1-86: Great job on improving the NewsletterModal component!

The changes in this file successfully address the bug described in issue #209 and meet the PR objectives. Key improvements include:

  1. Standardizing the unsubscribe action using the useUnsubscribe hook.
  2. Ensuring proper handling of unsubscribe credits and premium access.
  3. Improving user feedback during the unsubscribe process.
  4. Making the newsletter prop required for better type safety.

These changes will lead to a more consistent and reliable unsubscribe experience across the application. The code is now more maintainable and provides better user feedback.

Consider creating a separate file for the useUnsubscribe hook if it's used in multiple components. This would improve code organization and make it easier to maintain and test the unsubscribe logic independently.

Tools
Biome

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

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

(lint/suspicious/noExplicitAny)


[error] 2-3: All these imports are only used as types.

Importing the types with import type ensures that they are removed by the transpilers and avoids loading unnecessary modules.
Safe fix: Use import type.

(lint/style/useImportType)

apps/web/app/(app)/new-senders/NewSenders.tsx (1)

Line range hint 1-391: Implement useUnsubscribeButton hook in ActionCell.

The PR objectives mention standardizing the unsubscribe actions using the useUnsubscribeButton hook. However, this implementation is not visible in the current changes. To fully address the unsubscribe functionality bug, consider implementing the useUnsubscribeButton hook in the ActionCell component.

Here's a suggested approach:

  1. Import the useUnsubscribeButton hook at the top of the file:

    import { useUnsubscribeButton } from '@/hooks/useUnsubscribeButton';
  2. Modify the ActionCell component to use the hook:

    function ActionCell({
      item,
      userEmail,
      hasUnsubscribeAccess,
      mutate,
      refetchPremium,
      onOpenNewsletter,
      selected,
      userGmailLabels,
      openPremiumModal,
    }) {
      const { onUnsubscribe } = useUnsubscribeButton({
        newsletter: item,
        mutate,
        // Add other necessary props
      });
    
      // Use onUnsubscribe in your unsubscribe button's onClick handler
      // ...
    }

This change will ensure that both unsubscribe buttons (in the modal and the table row) use the same logic, addressing the inconsistency mentioned in the PR objectives.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 6ff6a65 and 32a67b2.

Files selected for processing (7)
  • apps/web/app/(app)/bulk-unsubscribe/BulkUnsubscribeSection.tsx (1 hunks)
  • apps/web/app/(app)/cold-email-blocker/ColdEmailList.tsx (1 hunks)
  • apps/web/app/(app)/cold-email-blocker/ColdEmailRejected.tsx (1 hunks)
  • apps/web/app/(app)/compose/selectors/color-selector.tsx (1 hunks)
  • apps/web/app/(app)/compose/selectors/link-selector.tsx (1 hunks)
  • apps/web/app/(app)/new-senders/NewSenders.tsx (1 hunks)
  • apps/web/app/(app)/stats/NewsletterModal.tsx (2 hunks)
Files skipped from review due to trivial changes (2)
  • apps/web/app/(app)/compose/selectors/color-selector.tsx
  • apps/web/app/(app)/compose/selectors/link-selector.tsx
Additional context used
Learnings (1)
apps/web/app/(app)/stats/NewsletterModal.tsx (1)
Learnt from: aryanprince
PR: elie222/inbox-zero#210
File: apps/web/app/(app)/stats/NewsletterModal.tsx:2-4
Timestamp: 2024-08-23T11:37:26.779Z
Learning: `MoreDropdown` is a React component and `useUnsubscribeButton` is a custom React hook, and they should not be imported using `import type`.
Biome
apps/web/app/(app)/stats/NewsletterModal.tsx

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

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

(lint/suspicious/noExplicitAny)


[error] 2-3: All these imports are only used as types.

Importing the types with import type ensures that they are removed by the transpilers and avoids loading unnecessary modules.
Safe fix: Use import type.

(lint/style/useImportType)

Additional comments not posted (9)
apps/web/app/(app)/cold-email-blocker/ColdEmailRejected.tsx (1)

68-73: Clarification needed on missing elements from PR objectives

While the changes improve the rendering logic, some key elements mentioned in the PR objectives are not visible in this component:

  1. The useUnsubscribeButton hook is not implemented here.
  2. The mutate prop is not being passed to the NewsletterModal.
  3. It's unclear how the unsubscribe functionality has been standardized between the modal and the table row action buttons.

Could you please clarify how these aspects are addressed in the overall solution? If they are implemented elsewhere, it would be helpful to see those changes as well.

To verify the implementation of the useUnsubscribeButton hook and the mutate prop, we can run the following script:

This script will help us locate where these elements are implemented and ensure they are correctly used across the codebase.

apps/web/app/(app)/stats/NewsletterModal.tsx (5)

1-2: LGTM: New imports for unsubscribe functionality

The addition of MoreDropdown and useUnsubscribe imports aligns with the PR objective of standardizing the unsubscribe actions. These components will help implement the consistent unsubscribe behavior across different parts of the application.


43-43: LGTM: Default value for mutate function

Providing a default value for the mutate function is a good practice. It ensures that mutate is always a function, preventing potential runtime errors if it's not passed as a prop. This change contributes to the robustness of the component and aligns with the PR objective of standardizing unsubscribe actions.


50-50: LGTM: Added premium access check for unsubscribe

The addition of the usePremium hook is a good improvement. It allows for checking unsubscribe access and provides a way to refetch premium status. This change aligns with the PR objective of properly handling unsubscribe credits and ensures that only users with appropriate access can perform unsubscribe actions.


54-60: LGTM: Centralized unsubscribe logic with useUnsubscribe hook

The addition of the useUnsubscribe hook is an excellent improvement. It centralizes the unsubscribe logic, which directly addresses the PR objective of standardizing unsubscribe actions across different parts of the application. This hook encapsulates all necessary dependencies and callbacks, including:

  1. Access check (hasUnsubscribeAccess)
  2. State update (mutate)
  3. Analytics tracking (posthog)
  4. Premium status update (refetchPremium)

This centralization will make it easier to maintain consistent behavior and will simplify future updates to the unsubscribe process.


72-86: LGTM: Improved unsubscribe button with loading state and proper event handling

The changes to the unsubscribe button are well-implemented and address the PR objectives:

  1. The button is now disabled during the unsubscribe process, preventing multiple attempts.
  2. The onClick event properly calls the onUnsubscribe function from the useUnsubscribe hook.
  3. A loading state is displayed, providing clear feedback to the user during the unsubscribe action.

These improvements ensure that the unsubscribe functionality in the modal works correctly and consistently with other parts of the application. The enhanced user feedback during the process is a nice touch that improves the overall user experience.

apps/web/app/(app)/cold-email-blocker/ColdEmailList.tsx (1)

Line range hint 1-324: Verify related changes in NewsletterModal component

The changes in this file partially address the unsubscribe functionality issue mentioned in the PR objectives. However, to ensure a complete solution, we should verify the changes made to the NewsletterModal component, which is not visible in this file.

Please confirm that the NewsletterModal component has been updated to use the useUnsubscribeButton hook as mentioned in the PR objectives. This is crucial for standardizing the unsubscribe actions across different parts of the application.

#!/bin/bash
# Search for useUnsubscribeButton usage in NewsletterModal
rg --type typescript -A 10 'useUnsubscribeButton.*NewsletterModal'
apps/web/app/(app)/bulk-unsubscribe/BulkUnsubscribeSection.tsx (1)

260-267: LGTM! These changes address the unsubscribe functionality issue.

The conditional rendering of NewsletterModal and the addition of the mutate prop effectively solve the bug described in issue #209. This ensures that unsubscribing via the newsletter modal will now correctly update the state and trigger necessary actions.

Key improvements:

  1. Conditional rendering prevents unnecessary renders when there's no opened newsletter.
  2. The mutate prop allows for state updates after unsubscribe actions.
  3. Accessing refreshInterval from props maintains consistency with other prop usage.

These changes align well with the PR objectives and address the concerns raised in the previous review.

apps/web/app/(app)/new-senders/NewSenders.tsx (1)

214-220: Improved modal rendering and prop passing.

The conditional rendering of NewsletterModal based on openedNewsletter is a good improvement. It prevents unnecessary rendering when there's no newsletter to display. Additionally, passing the newsletter prop to NewsletterModal aligns with the PR objectives of addressing the unsubscribe functionality bug.

Comment on lines +37 to +40
newsletter: Pick<Row, "name" | "lastUnsubscribeLink" | "autoArchived">;
onClose: (isOpen: boolean) => void;
refreshInterval?: number;
mutate?: () => Promise<any>;
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Approve newsletter prop change, but consider specifying mutate type

The change to make the newsletter prop required is good as it ensures the component always receives necessary data. However, for the mutate prop:

The newsletter prop change is approved.

The mutate prop uses the any type, which is generally discouraged as it bypasses TypeScript's type checking. Consider specifying a more precise return type for the Promise. If the exact type is unknown, you could use unknown instead of any:

mutate?: () => Promise<unknown>;

This maintains type safety while allowing flexibility in the return type.

Tools
Biome

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

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

(lint/suspicious/noExplicitAny)

Comment on lines 147 to 152
{openedRow && (
<NewsletterModal
newsletter={openedRow && { name: openedRow.fromEmail || "" }}
onClose={() => setOpenedRow(undefined)}
/>
)}
Copy link
Contributor

@coderabbitai coderabbitai bot Sep 24, 2024

Choose a reason for hiding this comment

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

💡 Codebase verification

⚠️ Potential issue

Add Missing mutate Prop to NewsletterModal in ColdEmailList.tsx

The NewsletterModal in ColdEmailList.tsx is missing the mutate prop, which is necessary for handling the unsubscribe functionality as outlined in the PR objectives. To ensure consistent behavior across all components, please add the mutate prop as shown below:

 {openedRow && (
   <NewsletterModal
-    newsletter={openedRow && { name: openedRow.fromEmail || "" }}
+    newsletter={{ name: openedRow.fromEmail || "" }}
     onClose={() => setOpenedRow(undefined)}
+    mutate={mutate}
   />
 )}

This addition aligns with the implementation in other components and ensures the unsubscribe functionality operates correctly.

Analysis chain

Simplify newsletter prop and add missing mutate prop

The conditional rendering of NewsletterModal is an improvement, but there are a couple of points to address:

  1. The newsletter prop can be simplified since openedRow is already checked in the conditional rendering.
  2. The mutate prop is missing, which is mentioned in the PR objectives as part of the fix for the unsubscribe functionality issue.

Please apply the following changes:

 {openedRow && (
   <NewsletterModal
-    newsletter={openedRow && { name: openedRow.fromEmail || "" }}
+    newsletter={{ name: openedRow.fromEmail || "" }}
     onClose={() => setOpenedRow(undefined)}
+    mutate={mutate}
   />
 )}

Can you confirm if these changes, along with updates in the NewsletterModal component (not visible in this file), fully address the unsubscribe functionality issue mentioned in the PR objectives? If not, what additional changes are needed?

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for NewsletterModal usage and implementation
rg --type typescript -A 10 'NewsletterModal'

Length of output: 103


Script:

#!/bin/bash
# Search for NewsletterModal usage and implementation in .ts and .tsx files
rg 'NewsletterModal' --glob '*.ts*' -A 10

Length of output: 9199

Copy link
Author

Choose a reason for hiding this comment

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

Good suggestion, resolved!

Copy link
Contributor

Choose a reason for hiding this comment

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

@aryanprince, happy to hear that the issue has been resolved!

(_/)
(•ᴗ•)
 /🐰\


If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!

Comment on lines 214 to 220
{openedNewsletter && (
<NewsletterModal
newsletter={openedNewsletter}
onClose={() => setOpenedNewsletter(undefined)}
refreshInterval={props.refreshInterval}
/>
)}
Copy link
Contributor

@coderabbitai coderabbitai bot Sep 24, 2024

Choose a reason for hiding this comment

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

⚠️ Potential issue

Inconsistent prop access and missing mutate prop.

There are two issues with the current implementation:

  1. The refreshInterval prop is accessed via props.refreshInterval, which is inconsistent with the component's parameter destructuring. It should be accessed directly as refreshInterval.

  2. The PR objectives mention passing a mutate prop to the NewsletterModal, but this is not visible in the changes. This prop is crucial for addressing the unsubscribe functionality bug.

To address these issues, please apply the following changes:

      {openedNewsletter && (
        <NewsletterModal
          newsletter={openedNewsletter}
          onClose={() => setOpenedNewsletter(undefined)}
-         refreshInterval={props.refreshInterval}
+         refreshInterval={refreshInterval}
+         mutate={mutate}
        />
      )}
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
{openedNewsletter && (
<NewsletterModal
newsletter={openedNewsletter}
onClose={() => setOpenedNewsletter(undefined)}
refreshInterval={props.refreshInterval}
/>
)}
{openedNewsletter && (
<NewsletterModal
newsletter={openedNewsletter}
onClose={() => setOpenedNewsletter(undefined)}
refreshInterval={refreshInterval}
mutate={mutate}
/>
)}

Copy link
Author

Choose a reason for hiding this comment

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

Thanks, fixed it now!

Copy link
Contributor

Choose a reason for hiding this comment

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

@aryanprince, glad to hear you've fixed it!

(^‿^)/


If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!

@aryanprince
Copy link
Author

aryanprince commented Sep 24, 2024

Note

Just a quick update for this PR

Summary

✅ Resolved conflicts, updated changes in this PR according to new code changes from main.

Major Changes

  • In terms of changes from my last commit on this PR (merge conflicts):
    • The old useUnsubscribeButton hook is now replaced by a newer useUnsubscribe hook instead.
    • Previously there was a <ButtonLoader2 /> component for a loading state, now it's just a prop on the <Button loading={true} /> component.

No other changes to this PR other than these.

Minor Changes

There were only 5 file changes in this PR previously, now there's 7.

2 of the extra files changed are due to lint-staged pre-commit step which forces me to format code in files apps/web/app/(app)/compose/selectors/color-selector.tsx and apps/web/app/(app)/compose/selectors/link-selector.tsx.

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.

bug: Unsubscribe credits not decrementing when using the newsletter modal button
3 participants