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

Replaced deprecated useMutation in questionnaire with tanstack's useMutation #9840

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

Conversation

abhimanyurajeesh
Copy link
Contributor

@abhimanyurajeesh abhimanyurajeesh commented Jan 8, 2025

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

Summary by CodeRabbit

  • New Features
    • Added feedback messages for questionnaire submission status: success and failure notifications.
  • Bug Fixes
    • Enhanced error handling for questionnaire submissions.
  • Refactor
    • Streamlined mutation handling and submission logic using @tanstack/react-query.

@abhimanyurajeesh abhimanyurajeesh requested a review from a team as a code owner January 8, 2025 08:47
Copy link
Contributor

coderabbitai bot commented Jan 8, 2025

Walkthrough

The pull request updates the QuestionnaireForm.tsx component by replacing the custom mutation handling approach with the useMutation hook from the @tanstack/react-query library. This change introduces a structured mutation function, enhances success and error handling, and simplifies the submission process. Additionally, new localization entries are added to provide user feedback upon successful questionnaire submission. Overall, the core functionality remains intact while improving code clarity and user experience.

Changes

File Change Summary
src/components/Questionnaire/QuestionnaireForm.tsx - Replaced custom mutation hook with @tanstack/react-query useMutation
- Updated mutation handling with direct success/error callbacks
- Simplified submitBatch function execution
- Changed loading state to isPending
public/locale/en.json - Added new entries: "questionnaire_submission_failed": "Failed to submit questionnaire"
- Added new entries: "questionnaire_submitted_successfully": "Questionnaire submitted successfully"
src/Utils/request/useMutation.ts - Removed deprecated useDeprecatedMutation hook

Assessment against linked issues

Objective Addressed Explanation
Replace deprecated data fetching utils with tanstack's useMutation [#9837]

Possibly related PRs

Suggested labels

good to merge

Suggested reviewers

  • rithviknishad
  • bodhish
  • Jacobjeevan

Poem

🐰 In the form where questions lie,
A new hook helps us fly high,
With success toasts and errors caught,
Clarity blooms in every thought,
A questionnaire's dance, now so bright,
Thanks to TanStack, all feels right! 🚀


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 51197b7 and ace9e7a.

📒 Files selected for processing (2)
  • src/Utils/request/useMutation.ts (0 hunks)
  • src/components/Questionnaire/QuestionnaireForm.tsx (11 hunks)
💤 Files with no reviewable changes (1)
  • src/Utils/request/useMutation.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/components/Questionnaire/QuestionnaireForm.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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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 Jan 8, 2025

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit ace9e7a
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/677e8ddcdceca300084ea668
😎 Deploy Preview https://deploy-preview-9840--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.

@abhimanyurajeesh
Copy link
Contributor Author

@rithviknishad requesting for a review.

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

🧹 Nitpick comments (3)
src/components/Questionnaire/QuestionnaireForm.tsx (3)

81-93: Enhance mutation implementation with better error handling and type safety

While the migration to TanStack's useMutation is good, consider these improvements:

  1. Add type safety for the error object
  2. Provide more context in error messages
  3. Consider adding retry strategy for transient failures
  const { mutate: submitBatch, isPending: isProcessing } = useMutation({
    mutationFn: mutate(routes.batchRequest),
+   retry: (failureCount, error) => failureCount < 3 && isRetryableError(error),
    onSuccess: () => {
      toast.success("Questionnaire submitted successfully");
      onSubmit?.();
    },
-   onError: (error: any) => {
+   onError: (error: Error & { results?: ValidationErrorResponse[] }) => {
      if (error.results) {
        handleSubmissionError(error.results as ValidationErrorResponse[]);
      }
-     toast.error("Failed to submit questionnaire");
+     toast.error(`Failed to submit questionnaire: ${error.message || 'Unknown error occurred'}`);
    },
  });

246-247: Add error boundary around mutation execution

The mutation execution could benefit from try-catch error handling to gracefully handle synchronous errors.

-   // Execute the mutation
-   submitBatch({ requests });
+   try {
+     // Execute the mutation
+     submitBatch({ requests });
+   } catch (error) {
+     console.error('Failed to execute mutation:', error);
+     toast.error('An unexpected error occurred while submitting the questionnaire');
+   }

212-214: Consider adding explicit type predicate for response filtering

The response filtering logic could be more explicit with a type predicate function.

+ const isNonStructuredResponse = (response: QuestionnaireResponse): boolean => !response.structured_type;
+
- const nonStructuredResponses = form.responses.filter(
-   (response) => !response.structured_type,
- );
+ const nonStructuredResponses = form.responses.filter(isNonStructuredResponse);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ca65ceb and eb07a6e.

📒 Files selected for processing (1)
  • src/components/Questionnaire/QuestionnaireForm.tsx (5 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Test
  • GitHub Check: OSSAR-Scan
🔇 Additional comments (2)
src/components/Questionnaire/QuestionnaireForm.tsx (2)

81-93: Overall implementation looks good!

The migration to TanStack's useMutation is a positive change that improves the code structure and maintainability. While there are some suggested improvements, the core implementation is solid.


1-1: Consider removing the custom mutate utility import

Since we're migrating to TanStack's useMutation, the custom mutate utility import might be redundant. Consider removing it if it's no longer needed elsewhere in the codebase.

Let's verify if the custom mutate utility is still needed:

Also applies to: 16-16

src/components/Questionnaire/QuestionnaireForm.tsx Outdated Show resolved Hide resolved
src/components/Questionnaire/QuestionnaireForm.tsx Outdated Show resolved Hide resolved
src/components/Questionnaire/QuestionnaireForm.tsx Outdated Show resolved Hide resolved
src/components/Questionnaire/QuestionnaireForm.tsx Outdated Show resolved Hide resolved
src/components/Questionnaire/QuestionnaireForm.tsx Outdated Show resolved Hide resolved
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

🧹 Nitpick comments (2)
src/components/Questionnaire/QuestionnaireForm.tsx (2)

82-95: Improve error handling type safety

The error handling could be more type-safe. Consider creating a custom type for the error response structure.

-    onError: (error: HTTPError) => {
-      const errorData = error.cause;
-      if (errorData?.results) {
+    onError: (error: HTTPError) => {
+      type BatchErrorResponse = {
+        results?: ValidationErrorResponse[];
+      };
+      const errorData = error.cause as BatchErrorResponse;
+      if (errorData?.results) {

Line range hint 214-248: Extract submission preparation logic for better readability

Consider extracting the request preparation logic into a separate helper function to improve code organization.

+  const prepareSubmissionRequest = (form: QuestionnaireFormState): BatchRequest | null => {
+    const nonStructuredResponses = form.responses.filter(
+      (response) => !response.structured_type,
+    );
+
+    if (nonStructuredResponses.length === 0) return null;
+
+    return {
+      url: `/api/v1/questionnaire/${form.questionnaire.slug}/submit/`,
+      method: "POST",
+      reference_id: form.questionnaire.id,
+      body: {
+        resource_id: encounterId,
+        encounter: encounterId,
+        patient: patientId,
+        results: nonStructuredResponses
+          .filter((response) => response.values.length > 0)
+          .map((response) => ({
+            question_id: response.question_id,
+            values: response.values.map((value) => ({
+              ...(value.value_code
+                ? { value_code: value.value_code }
+                : { value: String(value.value) }),
+            })),
+            note: response.note,
+            body_site: response.body_site,
+            method: response.method,
+          })),
+      },
+    };
+  };
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0a14340 and 51197b7.

📒 Files selected for processing (2)
  • public/locale/en.json (1 hunks)
  • src/components/Questionnaire/QuestionnaireForm.tsx (11 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • public/locale/en.json
🔇 Additional comments (2)
src/components/Questionnaire/QuestionnaireForm.tsx (2)

Line range hint 413-422: LGTM! Well-implemented loading state

The loading spinner implementation is clean and follows accessibility best practices by maintaining button dimensions and providing visual feedback.


Line range hint 1-434: Verify complete migration from deprecated data fetching

Let's ensure no deprecated data fetching utilities remain in the codebase.

✅ Verification successful

Migration to TanStack's useMutation is complete

All useMutation imports across the codebase are properly sourced from @tanstack/react-query, and no deprecated data fetching patterns were found. The changes in QuestionnaireForm.tsx are consistent with the rest of the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining usage of deprecated data fetching patterns
# This helps ensure the migration to TanStack's useMutation is complete

echo "Checking for deprecated mutation patterns..."
rg -l "useMutation.*from\s+['\"](?!@tanstack)" 

echo "Checking for old mutation utility imports..."
rg -l "import.*mutation.*from\s+['\"]@/Utils/request/mutation['\"]"

Length of output: 587


Script:

#!/bin/bash
# Check for useMutation imports
echo "=== Checking useMutation imports ==="
rg "import.*useMutation.*from" -g '!*.test.*' -g '!*.spec.*'

# Check for old mutation utility imports and usage
echo -e "\n=== Checking old mutation utilities ==="
rg "from\s+['\"]@/Utils/request/mutation['\"]"
rg "mutation\(" 

# Check for direct API calls without proper mutation handling
echo -e "\n=== Checking direct API calls ==="
rg "\.post\(|\.put\(|\.patch\(|\.delete\(" -g '*.tsx' -g '*.ts' -A 2

Length of output: 5020

@rithviknishad rithviknishad changed the title Replace deprecated data fetching utils. with tanstack's useMutation Replaced deprecated useMutation in questionnaire with tanstack's useMutation Jan 8, 2025
Copy link
Member

@rithviknishad rithviknishad left a comment

Choose a reason for hiding this comment

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

now that we are no longer using the old custom useMutation hook, let's delete that file too btw

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Replace deprecated data fetching utils. with tanstack's useQuery and useMutation
3 participants