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: history saving when navigate through parties #1350

Merged
merged 1 commit into from
Nov 7, 2024

Conversation

mbacherycz
Copy link
Contributor

@mbacherycz mbacherycz commented Nov 7, 2024

Closes: #1346

Hva er endret?

Dokumentasjon / Storybook / testdekning

  • Dokumentasjon er oppdatert eller ikke relevant / nødvendig.
  • Ny komponent har en eller flere stories i Storybook, eller så er ikke dette relevant.
  • Det er blitt lagt til nye tester / eksiterende tester er blitt utvidet, eller tester er ikke relevant.

Skjermbilder eller GIFs (valgfritt)

Summary by CodeRabbit

  • New Features

    • Enhanced party selection functionality with improved clarity and maintainability.
    • Added support for accessing the current location in the useParties hook.
  • Tests

    • Introduced a new test case for verifying the "Go-back" button functionality and its impact on UI elements.
    • Updated assertion logic for class checking in existing tests for better flexibility.

@mbacherycz mbacherycz requested a review from a team as a code owner November 7, 2024 13:28
Copy link

coderabbitai bot commented Nov 7, 2024

Warning

Rate limit exceeded

@mbacherycz has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 5 minutes and 3 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 0743d27 and 309e173.

📝 Walkthrough
📝 Walkthrough
📝 Walkthrough

Walkthrough

This pull request introduces changes to the useParties hook in the useParties.ts file, including the addition of the useLocation hook for accessing the current location object. The handlePartySelection function has been refactored for clarity, and the useEffect now triggers it based on query success and party presence. Additionally, the setSelectedPartyIds function has been updated for improved state handling. In the test file loginPartyContext.spec.ts, a new test case is added, and an existing assertion is modified to enhance the test suite's functionality.

Changes

File Path Change Summary
packages/frontend/src/api/useParties.ts - Added const location to access the current location object.
- Refactored handlePartySelection for clarity.
- Updated setSelectedPartyIds logic.
packages/frontend/tests/stories/loginPartyContext.spec.ts - Added new test for "Go-back button updates state and shows correct data and color theme."
- Updated assertion to use a regex for class name checking.

Possibly related PRs

Suggested labels

dev

Suggested reviewers

  • seanes

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

@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 (3)
packages/frontend/src/api/useParties.ts (2)

102-115: Consider enhancing utility functions with explicit returns and error handling.

The extracted utility functions improve code organization, but could benefit from:

  1. Explicit return types and undefined cases
  2. Error handling for edge cases

Consider these improvements:

-  const selectSpecificParty = () => {
+  const selectSpecificParty = (): PartyFieldsFragment | undefined => {
     const partyFromQuery = getSelectedPartyFromQueryParams(searchParams);
     return partyFromQuery && data?.parties?.find((party) => party.party.includes(partyFromQuery));
   };

-  const selectCurrentEndUser = () => {
+  const selectCurrentEndUser = (): PartyFieldsFragment | undefined => {
     return data?.parties?.find((party) => party.isCurrentEndUser);
   };

117-132: Enhance error handling in party selection logic.

While the party selection logic is well-structured, the error case could provide more context for debugging.

Consider enhancing the error message:

-        console.warn('No current end user found, unable to select default parties.');
+        console.warn(
+          'No current end user found, unable to select default parties.',
+          { availableParties: data?.parties?.length ?? 0 }
+        );
packages/frontend/tests/stories/loginPartyContext.spec.ts (1)

113-129: Consider enhancing test coverage and clarity.

The test effectively verifies the back button navigation behavior, but could be improved:

  1. The test title could be more specific, e.g., "Back navigation restores previous party selection state and theme"
  2. Consider adding URL parameter assertions like other tests:
expect(new URL(page.url()).searchParams.has('party')).toBe(false);
expect(new URL(page.url()).searchParams.has('allParties')).toBe(false);
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between e15c158 and 0743d27.

📒 Files selected for processing (2)
  • packages/frontend/src/api/useParties.ts (3 hunks)
  • packages/frontend/tests/stories/loginPartyContext.spec.ts (2 hunks)
🔇 Additional comments (5)
packages/frontend/src/api/useParties.ts (3)

4-4: LGTM: Import addition aligns with history management requirements.

The addition of useLocation is appropriate for tracking URL changes and managing navigation history.


Line range hint 1-153: Overall changes look good and align with PR objectives.

The refactoring improves code organization and fixes history-related issues by:

  1. Properly tracking URL changes with useLocation
  2. Extracting clear, single-responsibility utility functions
  3. Implementing proper party selection logic with error handling

The changes maintain good separation of concerns while fixing the history saving functionality.


134-139: Verify effect dependencies and potential update cycles.

While the effect's dependencies are more precise now, we should verify that:

  1. The effect doesn't create infinite update cycles through location changes
  2. Party selection persists correctly during navigation

Let's verify the implementation:

✅ Verification successful

Based on the search results, I can now generate a final response as we have sufficient information about the implementation:

No infinite update cycle risk detected in the effect implementation

The implementation is safe because:

  • handlePartySelection only updates URL params with replace: true option, preventing history stack growth
  • URL updates through setSearchParams are controlled and only occur in specific scenarios:
    • When selecting all organizations
    • When selecting a specific party
    • When stripping query params for party selection
  • The effect only runs when there's actual party data (data?.parties?.length > 0) and successful query (isSuccess)
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for potential infinite loops in effect handling
rg -A 5 "setSearchParams.*location" 

# Check for other useEffect implementations that might conflict
ast-grep --pattern 'useEffect($$$) {
  $$$
  setSearchParams($$$)
  $$$
}'

Length of output: 114


Script:

#!/bin/bash
# Let's check the implementation of handlePartySelection and its usage of URL params
rg -A 10 "handlePartySelection.*=" 

# Check for any setSearchParams usage in the file
rg -A 5 "setSearchParams" 

# Look for the implementation of the useParties hook
ast-grep --pattern 'const useParties = () => {
  $$$
}'

# Check for any location or search param related effects
rg -A 10 "useEffect.*location" 

Length of output: 5268

packages/frontend/tests/stories/loginPartyContext.spec.ts (2)

78-78: LGTM: Improved class assertion with regex pattern.

The change from strict class matching to regex pattern matching makes the test more resilient to CSS module variations while maintaining the core assertion logic.


113-129: Verify integration with useParties hook changes.

The test effectively covers the history saving functionality mentioned in the PR objectives. However, since this integrates with changes in the useParties hook, let's verify the complete implementation:

✅ Verification successful

Let me gather more information about the party selection implementation to verify the complete integration.


Based on the gathered information, I can now generate the final response:

Test correctly verifies party selection state management

The test aligns perfectly with the implementation in useParties hook which:

  • Manages party selection through URL search params
  • Handles state updates via setSearchParams
  • Preserves state during navigation through browser history

The test effectively verifies this implementation by:

  • Checking the correct party selection state after navigation
  • Verifying theme persistence
  • Testing the back navigation functionality
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the integration between the test and useParties hook implementation

# Test 1: Check if useParties hook handles history state
echo "Checking useParties hook implementation..."
rg -A 5 "useLocation|history" "packages/frontend/src/api/useParties.ts"

# Test 2: Verify no other tests are affected
echo "Checking for other history-related tests..."
rg -A 5 "goBack|history" "packages/frontend/tests"

Length of output: 1708


Script:

#!/bin/bash
# Check the party selection implementation and state management
echo "Checking party selection implementation..."
ast-grep --pattern 'function useParties() {
  $$$
}'

# Check for query param handling
echo "Checking query param handling..."
rg -A 5 "setSearchParams|getSelectedParty" "packages/frontend/src"

Length of output: 6177

@mbacherycz mbacherycz force-pushed the fix/history_back_btn_should_read_query branch from 8c18006 to 309e173 Compare November 7, 2024 13:48
@mbacherycz mbacherycz merged commit 4480ae4 into main Nov 7, 2024
21 checks passed
@mbacherycz mbacherycz deleted the fix/history_back_btn_should_read_query branch November 7, 2024 13:52
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.

fix: history back should read query correct selected party from state
2 participants