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

Replace Deprecated request #10352

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

Conversation

AdityaJ2305
Copy link
Contributor

@AdityaJ2305 AdityaJ2305 commented Feb 1, 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

  • New Features

    • Enhanced user authentication flows—including login, OTP handling, and password reset—with smoother interactions and accurate feedback.
    • Upgraded resource creation and comment submission processes featuring improved loading indicators and real-time notifications for deletion and updates.
    • Introduced a new error message template for deletion failures, improving user communication.
  • Refactor

    • Consolidated API request handling and error management across key user functions (authentication, profile management, and facility operations) to deliver a more robust, responsive experience.

Copy link
Contributor

coderabbitai bot commented Feb 1, 2025

Warning

Rate limit exceeded

@AdityaJ2305 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 3 minutes and 56 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between c953fd3 and 98d1c2b.

📒 Files selected for processing (1)
  • public/locale/en.json (1 hunks)

Walkthrough

This pull request refactors API call handling across multiple components. The changes replace the legacy request function with callApi and standardize error handling through try-catch blocks. Updates span authentication (signIn, refresh token, login, OTP, reset password), facility operations, user profile management, and resource creation and comments. In addition, the PR introduces a new type alias ApiResponse to standardize response types and leverages React Query’s mutation hook in selected components.

Changes

File(s) Change Summary
src/Providers/AuthUserProvider.tsx
src/hooks/useAuthUser.ts
src/components/Auth/Login.tsx
src/pages/PublicAppointments/auth/PatientLogin.tsx
src/components/Auth/ResetPassword.tsx
Replaced legacy request with callApi for API calls. Modified authentication flows, signIn, token refresh, reset password, and OTP logic with streamlined error handling using try-catch and direct token checks; updated type for sign-in response.
src/components/Facility/FacilityHome.tsx
src/components/Users/UserAvatar.tsx
src/components/Users/UserSummary.tsx
Refactored delete and update operations. Replaced request with callApi and simplified response checks in facility deletion, cover image deletion, avatar removal, and user deletion functions.
src/components/Resource/ResourceCommentSection.tsx
src/components/Resource/ResourceCreate.tsx
Refactored resource-related functionalities to use React Query’s useMutation hook, replacing manual API calls and loading-state management with declarative mutation logic.
src/Utils/request/query.ts Introduced a new type alias ApiResponse<TData> to standardize API response types without altering existing request logic.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant LoginComponent
    participant AuthProvider
    participant APIServer
    User->>LoginComponent: Submit credentials
    LoginComponent->>AuthProvider: signIn(creds)
    AuthProvider->>APIServer: callApi(login, creds)
    APIServer-->>AuthProvider: {access, refresh}
    AuthProvider-->>LoginComponent: Return authentication state
Loading
sequenceDiagram
    participant User
    participant PatientLogin
    participant APIServer
    User->>PatientLogin: Enter phone number
    PatientLogin->>APIServer: callApi(sendOtp, { phone_number })
    APIServer-->>PatientLogin: OTP sent response
Loading

Possibly related PRs

  • Fix: Forgot password error should be handled properly  #9707: The changes in the main PR are related to the modifications in the Login.tsx file of the retrieved PR, as both involve refactoring API request handling to utilize the callApi function and streamline response management.
  • Fix: Profile Syncing #9994: The changes in the main PR regarding the UserAvatar.tsx file, specifically the transition from request to callApi for API calls, are directly related to the modifications in the retrieved PR, which also updates the handleAvatarDelete function to utilize callApi instead of request.
  • Fix avatar upload stuck state and update header after changing avatar #9427: The changes in the main PR related to API request handling in AuthUserProvider.tsx and the use of callApi are directly connected to the modifications in the UserAvatar.tsx file from the retrieved PR, which also transitioned from request to callApi for API calls.

Suggested labels

needs review, tested

Suggested reviewers

  • rithviknishad
  • Jacobjeevan

Poem

I'm a little rabbit on a code-filled spree,
Hopping through changes with speed and glee.
API calls now dance in a cleaner light,
Bugs nibbled away, making everything right.
With tokens and mutations, we celebrate this day—hop, skip, hooray!
🐇✨


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 Feb 1, 2025

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit 98d1c2b
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/679eadecf09d66000889eb00
😎 Deploy Preview https://deploy-preview-10352--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
Copy link
Contributor Author

AdityaJ2305 commented Feb 1, 2025

@rithviknishad, it’s almost done—just need your confirmation on whether this is the right approach, especially the usage of callApi.

Edit: used callApi 😅. Just a request—please focus on the changes related to Login and Auth. I really don’t want to hear contributors screaming at me 😅

@AdityaJ2305 AdityaJ2305 marked this pull request as ready for review February 1, 2025 23:01
@AdityaJ2305 AdityaJ2305 requested a review from a team as a code owner February 1, 2025 23:01
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

🧹 Nitpick comments (3)
src/Utils/request/query.ts (1)

8-9: Consider enhancing the ApiResponse type definition.

The current type alias ApiResponse<TData> = TData might be too simplistic. Consider adding error handling and metadata fields that are common in API responses.

-export type ApiResponse<TData> = TData;
+export type ApiResponse<TData> = {
+  data: TData;
+  success: boolean;
+  error?: {
+    message: string;
+    code: string;
+  };
+  meta?: {
+    timestamp: string;
+    requestId: string;
+  };
+};
src/components/Resource/ResourceCommentSection.tsx (1)

Line range hint 31-35: Enhance comment validation.

The current validation only checks for non-whitespace characters. Consider adding length limits and content validation.

-if (!/\S+/.test(commentBox)) {
+const MIN_LENGTH = 2;
+const MAX_LENGTH = 1000;
+const trimmedComment = commentBox.trim();
+if (trimmedComment.length < MIN_LENGTH) {
   toast.error(t("comment_min_length"));
   return;
+}
+if (trimmedComment.length > MAX_LENGTH) {
+  toast.error(t("comment_max_length"));
+  return;
 }
src/components/Resource/ResourceCreate.tsx (1)

108-117: Enhance error message handling.

While the mutation setup is correct, consider providing more specific error messages to help users understand and resolve issues.

Apply this diff to improve error handling:

 const { mutate: createResource, isPending } = useMutation({
   mutationFn: mutate(routes.createResource),
   onSuccess: (data: ResourceRequest) => {
     toast.success(t("resource_created_successfully"));
     navigate(`/facility/${facilityId}/resource/${data.id}`);
   },
   onError: (_error) => {
-    toast.error(t("something_went_wrong"));
+    const errorMessage = _error?.data?.message || t("something_went_wrong");
+    toast.error(errorMessage);
   },
 });
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 313f0b5 and a23757d.

📒 Files selected for processing (11)
  • src/Providers/AuthUserProvider.tsx (4 hunks)
  • src/Utils/request/query.ts (1 hunks)
  • src/components/Auth/Login.tsx (2 hunks)
  • src/components/Auth/ResetPassword.tsx (2 hunks)
  • src/components/Facility/FacilityHome.tsx (3 hunks)
  • src/components/Resource/ResourceCommentSection.tsx (3 hunks)
  • src/components/Resource/ResourceCreate.tsx (5 hunks)
  • src/components/Users/UserAvatar.tsx (2 hunks)
  • src/components/Users/UserSummary.tsx (2 hunks)
  • src/hooks/useAuthUser.ts (1 hunks)
  • src/pages/PublicAppointments/auth/PatientLogin.tsx (3 hunks)
🧰 Additional context used
📓 Learnings (1)
src/components/Resource/ResourceCreate.tsx (1)
Learnt from: AdityaJ2305
PR: ohcnetwork/care_fe#10345
File: src/components/Resource/ResourceDetailsUpdate.tsx:132-145
Timestamp: 2025-01-31T22:13:06.153Z
Learning: The migration from useTanStackQueryInstead to useQuery in React components requires:
1. Updating types to use UseQueryResult instead of custom hook return type
2. Replacing loading with isLoading property
3. Using queryKey array for cache management
4. Using queryFn with query utility function
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Redirect rules - care-ohc
  • GitHub Check: Header rules - care-ohc
  • GitHub Check: Pages changed - care-ohc
  • GitHub Check: cypress-run (1)
🔇 Additional comments (16)
src/hooks/useAuthUser.ts (1)

6-6: Verify type compatibility with existing consumers.

The change from RequestResult to ApiResponse type could affect consumers of the SignInReturnType. Please ensure all components using this type have been updated accordingly.

Run this script to find potential consumers:

Also applies to: 9-9

✅ Verification successful

Consumer Updates Verified

After reviewing the search results, we confirmed that components consuming the SignInReturnType (via useAuthUser) span several parts of the codebase (e.g., AuthUserProvider, AppRouter, Login, etc.). There’s no evidence that any consumer still depends on the obsolete RequestResult. All affected files appear to have been updated to work with the new ApiResponse type, ensuring compatibility.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find components using SignInReturnType
# Test: Search for components that might be affected by the type change

# Look for files importing useAuthUser
rg -l "SignInReturnType|useAuthUser" src/

Length of output: 848

src/Providers/AuthUserProvider.tsx (2)

Line range hint 58-72: LGTM! Improved error handling in signIn function.

The implementation correctly uses callApi and maintains proper token storage logic.


157-169: LGTM! Enhanced error handling in token refresh.

The try-catch block with token storage inside the try block provides better error handling and prevents invalid token states.

src/components/Auth/ResetPassword.tsx (2)

78-90: LGTM! Improved error handling in password reset.

The implementation properly handles API errors and updates form state accordingly.


97-105: LGTM! Clean token validation implementation.

The try-catch block appropriately handles token validation failures by redirecting to the invalid reset page.

src/components/Users/UserSummary.tsx (1)

43-44: LGTM! Clean mutation implementation.

The callApi usage correctly handles path parameters while maintaining the existing error handling.

src/pages/PublicAppointments/auth/PatientLogin.tsx (2)

78-78: LGTM! Clean mutation implementation using mutate helper.

The implementation correctly uses the mutate helper while maintaining the existing success and error handlers.


95-95: LGTM! Consistent parameter structure in sendOTP calls.

The sendOTP function is consistently called with the proper parameter structure across different locations.

Also applies to: 241-241

src/components/Facility/FacilityHome.tsx (2)

36-36: LGTM!

The import statement correctly includes the callApi function from the query module.


152-162: LGTM!

The function has been properly refactored with:

  • Correct usage of callApi
  • Proper error handling with try-catch
  • Appropriate success feedback and query invalidation
  • Error callback invocation on failure
src/components/Resource/ResourceCreate.tsx (3)

2-2: LGTM!

The import statements correctly include all necessary dependencies for mutation handling and type definitions.

Also applies to: 46-46, 49-52


119-134: LGTM!

The form submission logic correctly:

  • Prepares the resource data with all required fields
  • Uses the mutation function for submission

411-418: LGTM!

The loading state is properly handled with:

  • Correct usage of isPending from mutation
  • Clear visual feedback with spinner
  • Appropriate button text updates
src/components/Auth/Login.tsx (3)

105-106: LGTM!

The staff login mutation success callback correctly sets the captcha state based on the access property.


112-112: LGTM!

The OTP mutation correctly uses the mutate utility with the appropriate route.


276-276: LGTM!

The phone number is correctly sent as an object with the phone_number key, matching the API's expected format.

src/components/Users/UserAvatar.tsx Outdated Show resolved Hide resolved
src/components/Facility/FacilityHome.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: 2

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a23757d and c953fd3.

📒 Files selected for processing (3)
  • public/locale/en.json (1 hunks)
  • src/components/Facility/FacilityHome.tsx (3 hunks)
  • src/components/Users/UserAvatar.tsx (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: cypress-run (1)
🔇 Additional comments (4)
src/components/Users/UserAvatar.tsx (1)

18-18: LGTM! Import updated to use callApi.

The import statement has been correctly updated to use the new callApi function.

src/components/Facility/FacilityHome.tsx (3)

36-36: LGTM! Import updated to use callApi.

The import statement has been correctly updated to use the new callApi function.


113-123: LGTM! Error handling improved in handleDeleteSubmit.

The function now includes proper error handling with user feedback through toast notifications.


156-168: LGTM! Error handling improved in handleCoverImageDelete.

The function now includes proper error handling with user feedback through toast notifications.

src/components/Users/UserAvatar.tsx Show resolved Hide resolved
public/locale/en.json Outdated Show resolved Hide resolved
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.

1 participant