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

feat(native-app): add useLocale hook #16357

Merged
merged 4 commits into from
Oct 15, 2024
Merged

feat(native-app): add useLocale hook #16357

merged 4 commits into from
Oct 15, 2024

Conversation

thoreyjona
Copy link
Contributor

@thoreyjona thoreyjona commented Oct 10, 2024

What

Add useLocale hook to use when sending locale into queries.

Why

Prevent typos like happened with applications and to be reusable

Checklist:

  • I have performed a self-review of my own code
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • Formatting passes locally with my changes
  • I have rebased against main before asking for a review

Summary by CodeRabbit

  • New Features

    • Introduced a custom hook useLocale for simplified locale management based on user preferences.
  • Improvements

    • Updated various application screens to utilize the new useLocale hook, enhancing the clarity and efficiency of locale handling.
    • Enhanced DocumentDetailScreen to improve document fetching logic and rendering based on the new locale management approach.

@thoreyjona thoreyjona requested a review from a team as a code owner October 10, 2024 14:39
Copy link
Contributor

coderabbitai bot commented Oct 10, 2024

Walkthrough

A new custom hook named useLocale has been introduced to manage locale preferences in the application. This hook retrieves the current locale from the preferences store and simplifies the locale handling in various application screens. The screens have been updated to utilize useLocale instead of directly accessing the preferences store, streamlining the process of determining the appropriate locale for queries.

Changes

File Path Change Summary
apps/native/app/src/hooks/use-locale.ts Added a new custom hook useLocale to access and determine the locale based on user preferences.
apps/native/app/src/screens/applications/applications-completed.tsx Updated to use useLocale() for locale instead of usePreferencesStore().
apps/native/app/src/screens/applications/applications-in-progress.tsx Updated to derive the locale variable from useLocale() instead of usePreferencesStore().
apps/native/app/src/screens/applications/applications-incomplete.tsx Transitioned to using useLocale() for the locale variable in the useListApplicationsQuery.
apps/native/app/src/screens/applications/applications.tsx Updated the variables object in useListApplicationsQuery to utilize useLocale() instead of the previous method.
apps/native/app/src/screens/document-detail/document-detail.tsx Updated DocumentDetailScreen to use useLocale() for the locale parameter in useGetDocumentQuery.

Possibly related PRs

Suggested reviewers

  • snaerseljan
  • mannipje

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.

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
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 (4)
apps/native/app/src/hooks/use-locale.ts (1)

3-6: Consider adding TypeScript type annotations for better type safety.

The useLocale hook implementation looks good and follows efficient state management practices by using usePreferencesStore. However, to improve type safety and adhere to TypeScript best practices, consider adding explicit type annotations.

Here's a suggested improvement:

export const useLocale = (): 'is' | 'en' => {
  const locale = usePreferencesStore(({ locale }: { locale: string }) => locale)
  return locale === 'is-IS' ? 'is' : 'en'
}

This change:

  1. Explicitly defines the return type of the hook as 'is' | 'en'.
  2. Adds type annotation for the locale parameter in the selector function.

These additions will enhance type checking and improve code readability.

apps/native/app/src/screens/applications/applications-incomplete.tsx (2)

42-42: Approved: useLocale implementation with a suggestion for type safety.

The direct usage of useLocale() in the query simplifies the locale determination logic and aligns with the PR objectives. It enhances reusability and reduces the likelihood of typographical errors.

Consider adding type annotation for better type safety:

locale: useLocale() as string,

This ensures that the locale property explicitly receives a string value, which might be expected by the GraphQL query.


Line range hint 1-62: Overall structure adheres to best practices with room for improvement.

The component follows NextJS and TypeScript best practices, including proper file structure, use of custom hooks, and correct typing for the component.

To further enhance type safety, consider adding explicit type annotations for the GraphQL query result:

const applicationsRes = useListApplicationsQuery<ListApplicationsQuery, ListApplicationsQueryVariables>({
  // ... existing code
});

This ensures that the query result and variables are properly typed, reducing the likelihood of runtime errors and improving developer experience with better autocomplete suggestions.

apps/native/app/src/screens/applications/applications-completed.tsx (1)

46-46: Approved: Effective use of useLocale hook

The implementation of useLocale() aligns well with the PR objectives. It simplifies locale handling, reduces the chance of typos, and enhances reusability. This change is consistent with the provided summary and maintains type safety through TypeScript inference.

Consider memoizing the locale value to optimize performance:

const locale = useLocale();

const applicationsRes = useListApplicationsQuery({
  variables: {
    input: {
      status: [
        ApplicationResponseDtoStatusEnum.Completed,
        ApplicationResponseDtoStatusEnum.Rejected,
        ApplicationResponseDtoStatusEnum.Approved,
      ],
    },
    locale,
  },
});

This approach can prevent unnecessary re-renders if useListApplicationsQuery is sensitive to prop changes.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 13ead6f and beeebf7.

📒 Files selected for processing (5)
  • apps/native/app/src/hooks/use-locale.ts (1 hunks)
  • apps/native/app/src/screens/applications/applications-completed.tsx (2 hunks)
  • apps/native/app/src/screens/applications/applications-in-progress.tsx (2 hunks)
  • apps/native/app/src/screens/applications/applications-incomplete.tsx (2 hunks)
  • apps/native/app/src/screens/applications/applications.tsx (2 hunks)
🧰 Additional context used
📓 Path-based instructions (5)
apps/native/app/src/hooks/use-locale.ts (1)

Pattern apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
apps/native/app/src/screens/applications/applications-completed.tsx (1)

Pattern apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
apps/native/app/src/screens/applications/applications-in-progress.tsx (1)

Pattern apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
apps/native/app/src/screens/applications/applications-incomplete.tsx (1)

Pattern apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
apps/native/app/src/screens/applications/applications.tsx (1)

Pattern apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
🔇 Additional comments (11)
apps/native/app/src/hooks/use-locale.ts (2)

1-1: LGTM: Import statement is correct and follows best practices.

The import statement correctly imports usePreferencesStore from the relative path. This adheres to NextJS best practices for importing custom hooks and stores.


3-6: Verify the usage of 'is-IS' locale code.

The implementation assumes that 'is-IS' is the correct locale code for Icelandic. It's important to ensure this is consistent with the rest of the application and follows ISO language codes.

Run the following script to verify the usage of 'is-IS' locale code across the codebase:

This script will help ensure consistency in locale handling across the application.

✅ Verification successful

Usage of 'is-IS' locale code is correct and consistent with ISO language codes and is uniformly applied across the application.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of 'is-IS' locale code across the codebase.

# Test: Search for 'is-IS' usage in TypeScript and JavaScript files
echo "Occurrences of 'is-IS' in TypeScript and JavaScript files:"
rg --type-add 'script:*.{ts,js}' --type script "'is-IS'" -n

# Test: Search for other potential Icelandic locale codes
echo "\nOther potential Icelandic locale codes:"
rg --type-add 'script:*.{ts,js}' --type script "'is'|'is-is'|'IS'|'IS-is'" -n

# Test: Search for locale-related configurations
echo "\nLocale-related configurations:"
rg --type json --type yaml "locale.*is" -n

Length of output: 64145

apps/native/app/src/screens/applications/applications-incomplete.tsx (1)

10-10: LGTM: Import statement for useLocale hook.

The import statement for the new useLocale hook is correctly added and follows React conventions for custom hooks. This change aligns with the PR objective of introducing the useLocale hook to reduce typographical errors and enhance reusability.

apps/native/app/src/screens/applications/applications-in-progress.tsx (3)

10-10: LGTM: New import for useLocale hook

The import statement for the useLocale hook is correctly placed and follows the existing import pattern in the file. This addition aligns with the PR objective of introducing the useLocale hook to reduce typographical errors and enhance reusability.


42-42: Excellent use of the new useLocale hook

The update to use useLocale() for the locale property in useListApplicationsQuery is a great improvement. It simplifies locale handling, eliminates the need for conditional checks, and adheres to React best practices by utilizing a custom hook for shared logic. This change effectively meets the PR objectives of reducing typographical errors and enhancing code reusability.


Line range hint 1-58: Overall assessment: Excellent adherence to best practices

The changes in this file maintain and improve upon existing best practices:

  1. NextJS best practices: The file structure and component organization remain consistent with NextJS conventions.
  2. TypeScript usage: The code continues to leverage TypeScript for type safety, particularly in component props and GraphQL query results.
  3. State management: The introduction of the useLocale hook simplifies state management by centralizing locale logic.
  4. Code organization: The component remains focused on its primary responsibility, with the new changes enhancing its clarity and maintainability.

These improvements align well with the PR objectives and contribute to a more robust and maintainable codebase.

apps/native/app/src/screens/applications/applications-completed.tsx (2)

10-10: LGTM: Import statement for useLocale

The import statement for the useLocale hook follows React naming conventions and uses a correct relative path. This adheres to NextJS best practices for organizing custom hooks.


Line range hint 1-63: Overall: Excellent adherence to best practices

The file applications-completed.tsx demonstrates strong adherence to NextJS best practices, efficient state management, and optimal use of TypeScript for type safety. The introduction of the useLocale hook enhances code reusability and maintainability.

Key observations:

  1. Proper file structure and naming conventions for a NextJS application.
  2. Effective use of React hooks (useState, useListApplicationsQuery, useLocale).
  3. Clear separation of concerns with custom hooks (useNavigationOptions, useConnectivityIndicator).
  4. Consistent use of TypeScript for improved type safety.

The changes introduced in this PR are focused and improve the overall code quality without disrupting the existing functionality.

apps/native/app/src/screens/applications/applications.tsx (3)

17-17: LGTM: Import statement for useLocale hook.

The import statement for the useLocale hook is correctly added and follows the expected relative path structure. This change aligns with the PR objective of introducing the useLocale hook to reduce typographical errors and enhance reusability.


Line range hint 1-207: Summary: Successful implementation of useLocale hook

The changes in this file successfully introduce the useLocale hook, aligning with the PR objectives. The modifications improve locale management by removing direct dependency on the preferences store, which should reduce the likelihood of typographical errors and enhance reusability.

Key points:

  1. The useLocale hook is correctly imported and used.
  2. The changes are minimal and focused, maintaining the overall structure and logic of the ApplicationsScreen component.
  3. The implementation adheres to NextJS best practices and makes efficient use of TypeScript.

These changes contribute to a more maintainable and consistent codebase. Great job!


107-107: LGTM: Usage of useLocale hook in query variables.

The useLocale hook is correctly implemented in the useListApplicationsQuery variables. This change simplifies the code and aligns with the PR objective of using the new hook for locale information in queries.

To ensure consistency, let's verify the usage of useLocale across the codebase:

✅ Verification successful

LGTM: Consistent usage of useLocale hook across the codebase.

All instances of locale handling have been updated to use the useLocale hook, and there are no remaining direct accesses to locale outside the hook's implementation. This ensures consistency and aligns with the PR's objective.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for consistent usage of useLocale hook

# Test 1: Search for useLocale import statements
echo "Checking useLocale import statements:"
rg --type typescript --type tsx "import.*useLocale.*from.*hooks/use-locale"

# Test 2: Search for useLocale usage in query variables
echo "\nChecking useLocale usage in query variables:"
rg --type typescript --type tsx "variables:.*\{.*locale:.*useLocale\(\).*\}"

# Test 3: Search for any remaining direct access to locale in preferences store
echo "\nChecking for any remaining direct access to locale in preferences store:"
rg --type typescript --type tsx "usePreferencesStore.*locale"

Length of output: 672


Script:

#!/bin/bash
# Description: Check for consistent usage of useLocale hook

# Test 1: Search for useLocale import statements
echo "Checking useLocale import statements:"
rg --type=ts --type=tsx "import.*useLocale.*from.*hooks/use-locale"

# Test 2: Search for useLocale usage in query variables
echo "\nChecking useLocale usage in query variables:"
rg --type=ts --type=tsx "variables:\s*\{\s*locale:\s*useLocale\(\)\s*\}"

# Test 3: Search for any remaining direct access to locale in preferences store
echo "\nChecking for any remaining direct access to locale in preferences store:"
rg --type=ts --type=tsx "usePreferencesStore.*locale"

Length of output: 631


Script:

#!/bin/bash
# Description: Check for consistent usage of useLocale hook

# Test 1: Search for useLocale import statements
echo "Checking useLocale import statements:"
rg -g "*.ts" -g "*.tsx" "import.*useLocale.*from.*hooks/use-locale"

# Test 2: Search for useLocale usage in query variables
echo "\nChecking useLocale usage in query variables:"
rg -g "*.ts" -g "*.tsx" "variables:\s*\{\s*locale:\s*useLocale\(\)\s*\}"

# Test 3: Search for any remaining direct access to locale in preferences store
echo "\nChecking for any remaining direct access to locale in preferences store:"
rg -g "*.ts" -g "*.tsx" "usePreferencesStore.*locale"

Length of output: 1215

Copy link

codecov bot commented Oct 10, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 36.73%. Comparing base (9a11ba4) to head (fb5f823).
Report is 1 commits behind head on main.

Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main   #16357      +/-   ##
==========================================
- Coverage   36.73%   36.73%   -0.01%     
==========================================
  Files        6808     6808              
  Lines      141061   141049      -12     
  Branches    40217    40213       -4     
==========================================
- Hits        51817    51808       -9     
+ Misses      89244    89241       -3     
Flag Coverage Δ
web 1.82% <ø> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

see 6 files with indirect coverage changes


Continue to review full report in Codecov by Sentry.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 9a11ba4...fb5f823. Read the comment docs.

@datadog-island-is
Copy link

datadog-island-is bot commented Oct 10, 2024

Datadog Report

Branch report: feat/use-locale-hook
Commit report: 78a5bbd
Test service: web

✅ 0 Failed, 84 Passed, 0 Skipped, 30.74s Total Time
➡️ Test Sessions change in coverage: 1 no change

@thoreyjona thoreyjona force-pushed the feat/use-locale-hook branch from beeebf7 to 8e7a41c Compare October 11, 2024 16:15
Copy link
Contributor

@snaerseljan snaerseljan left a comment

Choose a reason for hiding this comment

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

Nice thank you 🙏

@thoreyjona thoreyjona added the automerge Merge this PR as soon as all checks pass label Oct 14, 2024
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 (1)
apps/native/app/src/screens/document-detail/document-detail.tsx (1)

295-295: LGTM: Usage of useLocale hook

The replacement of usePreferencesStore with useLocale() for obtaining the locale is a good improvement. It aligns with the PR objective and should help reduce typographical errors.

For enhanced type safety, consider explicitly typing the locale parameter:

locale: useLocale() as string,

This ensures that the locale value matches the expected type in the query variables.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between beeebf7 and d994b5c.

📒 Files selected for processing (6)
  • apps/native/app/src/hooks/use-locale.ts (1 hunks)
  • apps/native/app/src/screens/applications/applications-completed.tsx (2 hunks)
  • apps/native/app/src/screens/applications/applications-in-progress.tsx (2 hunks)
  • apps/native/app/src/screens/applications/applications-incomplete.tsx (2 hunks)
  • apps/native/app/src/screens/applications/applications.tsx (2 hunks)
  • apps/native/app/src/screens/document-detail/document-detail.tsx (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (5)
  • apps/native/app/src/hooks/use-locale.ts
  • apps/native/app/src/screens/applications/applications-completed.tsx
  • apps/native/app/src/screens/applications/applications-in-progress.tsx
  • apps/native/app/src/screens/applications/applications-incomplete.tsx
  • apps/native/app/src/screens/applications/applications.tsx
🧰 Additional context used
📓 Path-based instructions (1)
apps/native/app/src/screens/document-detail/document-detail.tsx (1)

Pattern apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
🔇 Additional comments (2)
apps/native/app/src/screens/document-detail/document-detail.tsx (2)

33-33: LGTM: Import of useLocale hook

The addition of the useLocale hook import aligns with the PR objective and follows proper import conventions. This change will help reduce typographical errors and enhance reusability across the codebase.


Line range hint 1-524: Overall assessment: Positive changes with minor improvement suggestion

The introduction of the useLocale hook and its usage in the DocumentDetailScreen component aligns well with the PR objectives. These changes should improve code consistency and reduce the likelihood of typographical errors when dealing with locale information.

The implementation adheres to NextJS and TypeScript best practices, and the changes are minimal with no apparent breaking changes or performance issues. The suggestion for explicit typing of the locale parameter is a minor improvement for enhanced type safety.

Consider adding unit tests for the useLocale hook and updating the documentation to reflect these changes, as mentioned in the PR checklist.

To ensure that the useLocale hook is used consistently across the codebase, run the following script:

✅ Verification successful

Locale Hook Migration Verified

The verification confirms that there are no remaining instances of usePreferencesStore for locale handling. All locale-related functionalities have been successfully migrated to useLocale, ensuring consistency and adherence to the PR objectives.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining uses of usePreferencesStore for locale and compare with useLocale usage

echo "Checking for usePreferencesStore usage for locale:"
rg "usePreferencesStore\(\).*locale" --type typescript

echo "\nChecking for useLocale usage:"
rg "useLocale\(\)" --type typescript

echo "\nNote: Compare the outputs to ensure useLocale is being used consistently where appropriate."

Length of output: 546


Script:

#!/bin/bash
# Description: Check for any remaining uses of usePreferencesStore for locale and compare with useLocale usage

echo "Checking for usePreferencesStore usage for locale:"
rg "usePreferencesStore\(\).*locale" -g "*.ts" -g "*.tsx"

echo "\nChecking for useLocale usage:"
rg "useLocale\(\)" -g "*.ts" -g "*.tsx"

echo "\nNote: Compare the outputs to ensure useLocale is being used consistently where appropriate."

Length of output: 135703

@thoreyjona thoreyjona added automerge Merge this PR as soon as all checks pass and removed automerge Merge this PR as soon as all checks pass labels Oct 15, 2024
@kodiakhq kodiakhq bot merged commit 020a316 into main Oct 15, 2024
33 checks passed
@kodiakhq kodiakhq bot deleted the feat/use-locale-hook branch October 15, 2024 13:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
automerge Merge this PR as soon as all checks pass
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants