-
Notifications
You must be signed in to change notification settings - Fork 447
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
Fix loading state management in useQuery when requests are aborted #9222
Conversation
WalkthroughThe changes in this pull request involve modifications to error handling in the Changes
Assessment against linked issues
Possibly related PRs
Suggested labels
Suggested reviewers
📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
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? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
✅ Deploy Preview for care-ohc ready!
To edit notification comments on pull requests, go to your Netlify site configuration. |
Deploying care-fe with Cloudflare Pages
|
There was a problem hiding this 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 mergingThe options merging logic could potentially throw if
options
oroverrides
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 protectionWhile 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:
- Add proper error typing instead of
any
- Consider implementing exponential backoff for retries
- 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
📒 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
CARE Run #3960
Run Properties:
|
Project |
CARE
|
Branch Review |
rithviknishad/fix/usequery-abort-loading-state
|
Run status |
Passed #3960
|
Run duration | 05m 32s |
Commit |
977d766e68: Fix loading state management in useQuery when requests are aborted
|
Committer | Rithvik Nishad |
View all properties for this run ↗︎ |
Test results | |
---|---|
Failures |
0
|
Flaky |
0
|
Pending |
0
|
Skipped |
0
|
Passing |
135
|
View all changes introduced in this branch ↗︎ |
LGTM |
@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! 🙌 |
Proposed Changes
@ohcnetwork/care-fe-code-reviewers
Merge Checklist
Summary by CodeRabbit
New Features
request
function.useMutation
anduseQuery
hooks.Bug Fixes
useQuery
to prevent state updates when a request is aborted.useMutation
to manage response states more effectively.