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: TypeError in notification list #8935

Open
wants to merge 11 commits into
base: develop
Choose a base branch
from

Conversation

AdityaJ2305
Copy link
Contributor

@AdityaJ2305 AdityaJ2305 commented Oct 27, 2024

Proposed Changes

@ohcnetwork/care-fe-code-reviewers

Merge Checklist

  • Request for Peer Reviews

Note

I noticed there was an existing PR addressing this issue, but it seems inactive with unresolved conflicts. I’ve resolved the issue here to help move things forward.

Summary by CodeRabbit

  • Bug Fixes

    • Improved subscription and unsubscription logic to prevent errors when service workers are not supported.
    • Enhanced error handling during the unsubscribe process to ensure issues are captured.
  • Refactor

    • Simplified logic for determining subscription status for better readability.
    • Minor formatting adjustments for improved code clarity without affecting functionality.

Copy link

netlify bot commented Oct 27, 2024

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit 2500355
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/67349b7291ca790008e24d5f
😎 Deploy Preview https://deploy-preview-8935--care-ohc.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

@AdityaJ2305 AdityaJ2305 marked this pull request as ready for review October 27, 2024 07:20
@AdityaJ2305 AdityaJ2305 requested a review from a team as a code owner October 27, 2024 07:20
@bodhish
Copy link
Member

bodhish commented Oct 27, 2024

@AdityaJ2305 we would really try to merge the 1st PR for any issue, unless its super inactive for long.

Note to Reviewers: See if we can savage #8686, if we are going ahead with #8935 close the other and let the author know the reason.

Copy link

coderabbitai bot commented Nov 6, 2024

Walkthrough

The changes in this pull request focus on enhancing the subscription management logic within the NotificationsList.tsx component. Key updates include adding checks for the availability of navigator.serviceWorker and reg.pushManager before attempting to subscribe or unsubscribe users. The subscription status logic has been streamlined for improved readability. Error handling during the unsubscribe process remains intact, ensuring that errors are reported appropriately. Overall, these modifications aim to prevent potential TypeErrors and improve the robustness of the notification handling functionality.

Changes

Files Change Summary
src/components/Notifications/NotificationsList.tsx Updated subscription and unsubscription logic to include checks for navigator.serviceWorker and reg.pushManager. Simplified subscription status checks and preserved error handling. Minor formatting adjustments made.

Assessment against linked issues

Objective Addressed Explanation
Safely check for the availability of the service worker and handle undefined push manager subscription object. (#8006)

🐰 "In the land of code where bunnies hop,
We check for workers, we won't stop!
With subscriptions safe and errors caught,
Our notifications dance, oh what a thought!
So here’s to logic, clear and bright,
In the world of code, we take flight!" 🐇✨


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

@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)
src/components/Notifications/NotificationsList.tsx (2)

264-267: Add user feedback for unsupported browsers.

Good addition of the service worker availability check. However, users should be informed when notifications are not supported.

Consider adding user feedback:

 if (!navigator.serviceWorker) {
+  Warn({
+    msg: t("notifications_not_supported_in_browser"),
+  });
   return;
 }

305-336: Consider modernizing with async/await pattern.

The pushManager check effectively prevents the TypeError. However, the nested promise chain could be simplified.

Consider refactoring to use async/await for better readability:

-    navigator.serviceWorker.ready
-      .then(function (reg) {
-        if (reg.pushManager) {
-          setIsSubscribing(true);
-          reg.pushManager
-            .getSubscription()
-            .then(function (subscription) {
-              subscription
-                ?.unsubscribe()
-                .then(async function (_successful) {
-                  const data = {
-                    pf_endpoint: "",
-                    pf_p256dh: "",
-                    pf_auth: "",
-                  };
-                  await request(routes.updateUserPnconfig, {
-                    pathParams: { username: username },
-                    body: data,
-                  });
-                  setIsSubscribed("NotSubscribed");
-                  setIsSubscribing(false);
-                })
-                .catch(function (_e) {
-                  Error({
-                    msg: t("unsubscribe_failed"),
-                  });
-                });
-            })
-            .catch(function (_e) {
-              Error({ msg: t("subscription_error") });
-            });
-        }
-      })
-      .catch(function (_e) {
-        Sentry.captureException(_e);
-      });
+    try {
+      const reg = await navigator.serviceWorker.ready;
+      if (!reg.pushManager) return;
+      
+      setIsSubscribing(true);
+      const subscription = await reg.pushManager.getSubscription();
+      
+      try {
+        await subscription?.unsubscribe();
+        await request(routes.updateUserPnconfig, {
+          pathParams: { username: username },
+          body: {
+            pf_endpoint: "",
+            pf_p256dh: "",
+            pf_auth: "",
+          },
+        });
+        setIsSubscribed("NotSubscribed");
+      } catch (e) {
+        Error({ msg: t("unsubscribe_failed") });
+      } finally {
+        setIsSubscribing(false);
+      }
+    } catch (e) {
+      Sentry.captureException(e);
+      Error({ msg: t("subscription_error") });
+    }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 6b57124 and a603b20.

📒 Files selected for processing (1)
  • src/components/Notifications/NotificationsList.tsx (2 hunks)
🔇 Additional comments (1)
src/components/Notifications/NotificationsList.tsx (1)

Line range hint 264-336: Verify the TypeError fix in different browser contexts.

The implemented checks should prevent the TypeError. However, we should verify the fix across different scenarios.

Let's check for any remaining potential issues:

✅ Verification successful

Service Worker and PushManager checks are properly implemented

The code changes effectively prevent the TypeError through comprehensive checks:

  • All direct serviceWorker accesses have proper existence checks
  • The pushManager is verified before usage
  • Optional chaining is used appropriately in event listeners
  • Error handling is implemented for subscription operations

Key protected locations:

  • NotificationsList.tsx: Guards with if (!navigator.serviceWorker) and if (reg.pushManager)
  • useMessageListener.ts: Uses optional chaining for event listeners
  • useNotificationSubscriptionState.ts: Implements proper error handling for subscription states
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other potential unchecked service worker or pushManager usages
rg -A 3 'serviceWorker|pushManager' --type ts --type tsx

Length of output: 86


Script:

#!/bin/bash
# Search for other potential unchecked service worker or pushManager usages with correct file extensions
rg -A 3 'serviceWorker|pushManager' --type typescript --type tsx --type jsx

Length of output: 112


Script:

#!/bin/bash
# Search for service worker and pushManager usages without file type restrictions
rg -A 3 'serviceWorker|pushManager'

Length of output: 3113

Copy link

@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)
src/components/Notifications/NotificationsList.tsx (2)

264-267: Add user feedback for unsupported browsers.

Good addition of the service worker availability check. However, users should be informed when notifications aren't supported.

 if (!navigator.serviceWorker) {
+  Warn({ msg: t("notifications_not_supported") });
   return;
 }

302-339: Improve error handling and user feedback in unsubscribe function.

The async/await refactor and error handling additions are good improvements. However, there are a few suggestions for enhancement:

  1. Add user feedback for unsupported pushManager:
-  if (!reg.pushManager) return;
+  if (!reg.pushManager) {
+    Warn({ msg: t("push_notifications_not_supported") });
+    setIsSubscribing(false);
+    return;
+  }
  1. Simplify the nested try-catch:
 const subscription = await reg.pushManager.getSubscription();
 
 if (subscription) {
   try {
     await subscription.unsubscribe();
-
-    const data = {
-      pf_endpoint: "",
-      pf_p256dh: "",
-      pf_auth: "",
-    };
-
-    await request(routes.updateUserPnconfig, {
-      pathParams: { username },
-      body: data,
-    });
-
-    setIsSubscribed("NotSubscribed");
-  } catch (e) {
-    Error({ msg: t("unsubscribe_failed") });
-  } finally {
-    setIsSubscribing(false);
-  }
-} else {
-  setIsSubscribing(false);
-}
+    await request(routes.updateUserPnconfig, {
+      pathParams: { username },
+      body: {
+        pf_endpoint: "",
+        pf_p256dh: "",
+        pf_auth: "",
+      },
+    });
+    setIsSubscribed("NotSubscribed");
+  } catch (e) {
+    Error({ msg: t("unsubscribe_failed") });
+  }
+}
+setIsSubscribing(false);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between a603b20 and b708922.

📒 Files selected for processing (1)
  • src/components/Notifications/NotificationsList.tsx (2 hunks)
🔇 Additional comments (1)
src/components/Notifications/NotificationsList.tsx (1)

Line range hint 264-339: Verify service worker and pushManager availability checks.

The implementation successfully addresses the TypeError by adding proper checks for service worker and pushManager availability. Let's verify the usage of these APIs across the codebase:

✅ Verification successful

Based on the search results, I can now provide a comprehensive verification. The code shows consistent patterns of service worker and pushManager checks across the codebase:

Service worker and pushManager checks are properly implemented across the codebase

  • The main implementation in NotificationsList.tsx has proper guards
  • The shared hook useNotificationSubscriptionState.ts follows the same pattern of checking service worker availability
  • All pushManager usages are properly guarded with existence checks
  • The error handling is consistent across all notification-related implementations
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for other instances of pushManager usage that might need similar guards

# Test 1: Search for direct pushManager usage
echo "Checking for pushManager usage..."
rg "pushManager"

# Test 2: Search for service worker registration patterns
echo "Checking for service worker registration patterns..."
rg "serviceWorker.ready"

# Test 3: Search for subscription-related code
echo "Checking for subscription-related code..."
rg "getSubscription|subscribe|unsubscribe"

Length of output: 7257

@AdityaJ2305
Copy link
Contributor Author

@coderabbitai full review

Copy link

coderabbitai bot commented Nov 6, 2024

@AdityaJ2305, I will perform a full review of the pull request.

✅ Actions performed

Full review triggered.

Copy link

@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)
src/components/Notifications/NotificationsList.tsx (2)

264-267: Add user feedback for unsupported browsers.

The guard clause for navigator.serviceWorker availability is good, but users should be informed why the subscription failed.

Consider adding user feedback:

 if (!navigator.serviceWorker) {
+  Error({ msg: t("browser_not_supported") });
   return;
 }

Also, you can simplify the code by using isSubscribed directly:

-const status = isSubscribed;
-if (["NotSubscribed", "SubscribedOnAnotherDevice"].includes(status)) {
+if (["NotSubscribed", "SubscribedOnAnotherDevice"].includes(isSubscribed)) {

302-339: Improve error handling specificity and consistency.

The refactored unsubscribe function with proper error handling and state management looks good. The checks for pushManager availability and proper try-catch blocks effectively prevent the TypeError.

Consider these minor improvements:

  1. Make error messages more specific:
-          Error({ msg: t("unsubscribe_failed") });
+          Error({ msg: t("unsubscribe_failed_subscription_removal") });
  1. Remove excessive empty lines for consistent spacing:
     try {
       const reg = await navigator.serviceWorker.ready;
-
       if (!reg.pushManager) {
         Error({ msg: t("unsubscribe_failed") });
         return;
       }
-
       setIsSubscribing(true);
-
       const subscription = await reg.pushManager.getSubscription();
-
       if (subscription) {
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 6b57124 and 8c1f489.

📒 Files selected for processing (1)
  • src/components/Notifications/NotificationsList.tsx (2 hunks)

Copy link

👋 Hi, @AdityaJ2305,
Conflicts have been detected against the base branch. Please rebase your branch against the base branch.


This message is automatically generated by prince-chrismc/label-merge-conflicts-action so don't hesitate to report issues/improvements there.

@github-actions github-actions bot added the merge conflict pull requests with merge conflict label Nov 12, 2024
@github-actions github-actions bot removed the merge conflict pull requests with merge conflict label Nov 12, 2024
@AdityaJ2305
Copy link
Contributor Author

Hey @bodhish , This PR is labeled as “blocked.” I’ve made the requested changes requested by coderabbit and resolved the conflicts. Could you clarify how blocked PRs are typically handled and if there’s anything specific I should do?

@github-actions github-actions bot added needs-triage question Further information is requested labels Nov 13, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
blocked needs-triage question Further information is requested
Projects
None yet
Development

Successfully merging this pull request may close these issues.

TypeError in NotificationsList Component on Service Worker Subscription Fetch
2 participants