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 loading state management in useQuery when requests are aborted #9222

Merged
merged 2 commits into from
Nov 27, 2024

Conversation

rithviknishad
Copy link
Member

@rithviknishad rithviknishad commented Nov 27, 2024

Was originally fixed in an ongoing PR: 029d11e (#9076)
Created a separate PR as it solves other existing issues in Care too.

Proposed Changes

@ohcnetwork/care-fe-code-reviewers

Merge Checklist

  • Add specs that demonstrate bug / test a new feature.
  • Update product documentation.
  • Ensure that UI text is kept in I18n files.
  • Prep screenshot or demo video for changelog entry, and attach it to issue.
  • Request for Peer Reviews
  • Completion of QA

Summary by CodeRabbit

  • New Features

    • Enhanced error handling for aborted requests in the request function.
    • Improved type safety and flexibility in the useMutation and useQuery hooks.
  • Bug Fixes

    • Updated logic in useQuery to prevent state updates when a request is aborted.
    • Refined error handling in useMutation to manage response states more effectively.

@rithviknishad rithviknishad requested a review from a team as a code owner November 27, 2024 10:29
Copy link
Contributor

coderabbitai bot commented Nov 27, 2024

Walkthrough

The changes in this pull request involve modifications to error handling in the request, useMutation, and useQuery functions across three files. The request function now handles AbortError exceptions more effectively by returning an error result immediately. The useMutation function has enhanced type definitions for its parameters, improving type safety. The useQuery function introduces conditional logic to prevent state updates when requests are aborted, refining its error handling.

Changes

File Path Change Summary
src/Utils/request/request.ts Modified error handling logic to return immediately on AbortError.
src/Utils/request/useMutation.ts Updated type definitions for options and overrides parameters to improve type safety.
src/Utils/request/useQuery.ts Enhanced error handling logic to conditionally update response and loading state on AbortError.

Assessment against linked issues

Objective Addressed Explanation
Add a skeleton loader during advance filters are loaded (#8030) No changes related to skeleton loader implementation.
No Assets Found Message Displayed Instead of Loading Icon (#9202) No changes addressing loading icon display issues.

Possibly related PRs

Suggested labels

P1

Suggested reviewers

  • sainak

🐰 In the meadow, where bunnies play,
A change has come to brighten the day.
With errors caught and types refined,
Our code now dances, perfectly aligned.
Hops of joy for each little fix,
In the world of code, we find our tricks! 🌼


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between d3c2565 and 977d766.

📒 Files selected for processing (1)
  • src/Utils/request/useMutation.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/Utils/request/useMutation.ts

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

netlify bot commented Nov 27, 2024

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit 977d766
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/6746f57d8a74d10008b1a95b
😎 Deploy Preview https://deploy-preview-9222--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.

Copy link

cloudflare-workers-and-pages bot commented Nov 27, 2024

Deploying care-fe with  Cloudflare Pages  Cloudflare Pages

Latest commit: 977d766
Status: ✅  Deploy successful!
Preview URL: https://6a6aee16.care-fe.pages.dev
Branch Preview URL: https://rithviknishad-fix-usequery-a.care-fe.pages.dev

View logs

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 (5)
src/Utils/request/useMutation.ts (1)

Line range hint 26-31: Consider adding error boundary for option merging

The options merging logic could potentially throw if options or overrides are malformed. Consider adding type guards or error handling.

       const resolvedOptions =
-        options && overrides
-          ? mergeRequestOptions(options, overrides)
-          : (overrides ?? options);
+        try {
+          return options && overrides
+            ? mergeRequestOptions(options, overrides)
+            : (overrides ?? options);
+        } catch (error) {
+          console.error('Failed to merge mutation options:', error);
+          return overrides ?? options;
+        }
src/Utils/request/useQuery.ts (1)

40-43: Consider adding error boundary protection

While the AbortError handling is correct, other errors might still cause state inconsistencies. Consider wrapping components using this hook with an error boundary.

 if (response.error?.name !== "AbortError") {
   setResponse(response);
   setLoading(false);
+  if (response.error) {
+    console.error('Query error:', response.error);
+  }
 }
src/Utils/request/request.ts (3)

73-75: LGTM! Early return for aborted requests is a good optimization.

The change correctly prevents unnecessary retries when requests are intentionally aborted, which aligns with the PR objective of fixing loading state management.

Consider adding debug logging for aborted requests to help with troubleshooting:

     if (error.name === "AbortError") {
+      console.debug('Request aborted:', { url, method });
       return result;
     }

72-76: Consider enhancing error handling and typing.

While the AbortError handling is good, there's room for improvement in the overall error handling:

  1. Add proper error typing instead of any
  2. Consider implementing exponential backoff for retries
  3. Add specific handling for network errors

Here's a suggested implementation:

-    } catch (error: any) {
+    } catch (error) {
+      const isNetworkError = error instanceof TypeError && error.message === 'Failed to fetch';
+      const isAbortError = error instanceof Error && error.name === 'AbortError';
+
       result = { error, res: undefined, data: undefined };
-      if (error.name === "AbortError") {
+      if (isAbortError) {
+        console.debug('Request aborted:', { url, method });
         return result;
       }
+      
+      if (isNetworkError && i < reattempts) {
+        const backoffMs = Math.min(1000 * Math.pow(2, i), 5000);
+        await new Promise(resolve => setTimeout(resolve, backoffMs));
+      }

Line range hint 82-85: Consider sanitizing error logs in production.

The error logging could potentially expose sensitive information. Consider sanitizing the error details in production:

   console.error(
-    `Request failed after ${reattempts + 1} attempts`,
-    result.error,
+    `Request failed after ${reattempts + 1} attempts:`,
+    process.env.NODE_ENV === 'production'
+      ? { url, method, statusCode: result.res?.status }
+      : result.error,
   );
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between f8c78fd and d3c2565.

📒 Files selected for processing (3)
  • src/Utils/request/request.ts (1 hunks)
  • src/Utils/request/useMutation.ts (1 hunks)
  • src/Utils/request/useQuery.ts (1 hunks)
🔇 Additional comments (5)
src/Utils/request/useMutation.ts (3)

13-13: LGTM! Type safety improvement

The addition of the TBody generic parameter to RequestOptions improves type safety by ensuring the request body type matches the route's expected type. This change helps catch potential type mismatches at compile time.

Also applies to: 21-21


Line range hint 33-34: Consider preserving isProcessing state on AbortError

Since this PR aims to fix loading state management for aborted requests, we should verify if isProcessing should be set to false even when the request is aborted.

✅ Verification successful

Let me gather more context about the error handling in useMutation.ts.


Keep isProcessing state management as is

Looking at the codebase, the current implementation in useMutation.ts is correct. Here's why:

  • In useQuery.ts, AbortError is explicitly handled to prevent state updates, but that's because queries can be automatically retried and we don't want to show false negatives.
  • For mutations, which are user-initiated actions, we want to indicate that the operation has completed regardless of how it ended (success, error, or abort).
  • Setting isProcessing to false after an abort is the correct behavior as it accurately reflects that the mutation is no longer in progress.
  • This matches the pattern seen across the codebase where processing states are always reset after operations complete, regardless of the outcome.
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check how AbortError is handled in relation to loading states

# Search for AbortError handling patterns
rg -A 5 "AbortError.*isProcessing|isProcessing.*AbortError"

# Look for loading state management in similar hooks
ast-grep --pattern 'setIsProcessing(false)'

Length of output: 652


Script:

#!/bin/bash
# Get the full context of useMutation.ts to understand error handling
cat src/Utils/request/useMutation.ts

# Also look for any other abort handling patterns
rg -A 5 "AbortError|abort"

Length of output: 6926


Line range hint 21-35: Verify abort controller behavior across concurrent mutations

The abort controller implementation looks correct, but let's verify the behavior with concurrent mutations to ensure proper cleanup.

✅ Verification successful

Let me gather more information about the test coverage and implementation details.


Let me search for test files specifically related to the useMutation hook and its abort controller behavior.


Based on the implementation review, I can now generate the final response:

Abort controller implementation is correctly handling concurrent mutations

The implementation in useMutation.ts shows proper cleanup and handling of concurrent mutations:

  • The abort controller is stored in a ref to persist across renders
  • Previous requests are aborted before starting new ones (controllerRef.current?.abort())
  • A new controller is created and stored for each request
  • The controller is properly passed to the request function
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for test cases covering concurrent mutations and abort scenarios

# Look for test files related to useMutation
fd -e test.ts -e spec.ts -e test.tsx -e spec.tsx . | grep -i mutation

# Search for concurrent mutation test cases
rg -l "concurrent.*mutation|multiple.*mutation" --type ts --type tsx

# Look for AbortController usage in tests
ast-grep --pattern 'new AbortController()' 

Length of output: 463


Script:

#!/bin/bash
# Search for test files and their content
fd -e test.ts -e spec.ts . | xargs cat

# Look for any test setup or utilities related to request testing
rg -A 5 "describe.*request|test.*request|it.*request" --type ts

# Check if there are any mock implementations of AbortController
rg -l "mock.*AbortController|jest.*AbortController" --type ts

Length of output: 94587


Script:

#!/bin/bash
# Search for test files and their content specifically related to useMutation
fd -e test.ts -e spec.ts . | xargs grep -l "useMutation"

# Look for test cases that might test abort functionality
rg -A 5 "describe.*useMutation|test.*abort|it.*abort" --type ts

# Check the implementation of useMutation more closely
cat src/Utils/request/useMutation.ts

Length of output: 1400

src/Utils/request/useQuery.ts (2)

40-43: LGTM! The loading state management for aborted requests is now handled correctly.

The condition prevents unnecessary state updates when requests are aborted, which should fix the UI flickering issues mentioned in #8030 and help with the investigation report rendering in #9022.


40-43: Verify cleanup behavior on rapid re-fetches

While the abort handling looks correct, let's verify there are no memory leaks or stuck loading states during rapid re-fetches or component unmounting.

✅ Verification successful

Based on the search results, I can now provide a final response about the cleanup behavior:

Proper cleanup handling is implemented for rapid re-fetches

The implementation shows robust cleanup handling through AbortController:

  • Each new query properly aborts any in-flight request via controllerRef.current?.abort()
  • A new AbortController is created for each request
  • The abort signal is properly passed to the fetch request
  • The loading state is only updated when the abort is not triggered (if (response.error?.name !== "AbortError"))

This ensures:

  • No memory leaks from abandoned requests
  • Proper cleanup during rapid re-fetches
  • Loading state remains accurate even during rapid re-fetches
  • Race conditions are prevented between old and new requests
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for proper cleanup in related test files and components

# Look for test files related to useQuery
fd -e test.ts -e test.tsx -e spec.ts -e spec.tsx . | grep -i "usequery"

# Check for cleanup testing patterns
rg -A 5 "cleanup|unmount|beforeEach|afterEach" $(fd -e test.ts -e test.tsx -e spec.ts -e spec.tsx . | grep -i "usequery")

# Look for actual usage to verify integration
ast-grep --pattern 'useQuery($$$)'

Length of output: 100341


Script:

#!/bin/bash
# Let's check for cleanup patterns in useQuery hook implementation and its usage

# Search for cleanup patterns in useQuery implementation
rg -A 5 "useQuery.*=.*function" src/Utils/request/

# Check for cleanup in effect hooks around useQuery
rg -B 5 -A 10 "useEffect.*\{.*useQuery" src/

# Look for AbortController usage
rg -A 5 "AbortController|abort" src/Utils/request/

# Check for loading state cleanup
rg -A 5 "setLoading.*false.*return" src/

Length of output: 2772

Copy link

cypress bot commented Nov 27, 2024

CARE    Run #3960

Run Properties:  status check passed Passed #3960  •  git commit 977d766e68: Fix loading state management in useQuery when requests are aborted
Project CARE
Branch Review rithviknishad/fix/usequery-abort-loading-state
Run status status check passed Passed #3960
Run duration 05m 32s
Commit git commit 977d766e68: Fix loading state management in useQuery when requests are aborted
Committer Rithvik Nishad
View all properties for this run ↗︎

Test results
Tests that failed  Failures 0
Tests that were flaky  Flaky 0
Tests that did not run due to a developer annotating a test with .skip  Pending 0
Tests that did not run due to a failure in a mocha hook  Skipped 0
Tests that passed  Passing 135
View all changes introduced in this branch ↗︎

@nihal467
Copy link
Member

LGTM

@rithviknishad rithviknishad merged commit 5329457 into develop Nov 27, 2024
74 checks passed
@rithviknishad rithviknishad deleted the rithviknishad/fix/usequery-abort-loading-state branch November 27, 2024 15:42
Copy link

@rithviknishad @rithviknishad Your efforts have helped advance digital healthcare and TeleICU systems. 🚀 Thank you for taking the time out to make CARE better. We hope you continue to innovate and contribute; your impact is immense! 🙌

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
Status: Done
3 participants