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: Avoid multiple browser history push when navigating or using search bar. #1351

Merged
merged 1 commit into from
Nov 11, 2024

Conversation

mbacherycz
Copy link
Contributor

@mbacherycz mbacherycz commented Nov 8, 2024

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 search functionality in the SearchBar component, improving how search parameters are managed in the URL.
    • Updated handling of URL parameters in the Inbox component for better browser history management.
  • Bug Fixes

    • Revised test for the "Go-back button" to ensure it correctly clears the search bar value and updates the URL parameters.

@mbacherycz mbacherycz requested a review from a team as a code owner November 8, 2024 12:00
Copy link

coderabbitai bot commented Nov 8, 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 15 minutes and 39 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 03961df and 2ac5628.

📝 Walkthrough
📝 Walkthrough
📝 Walkthrough
📝 Walkthrough

Walkthrough

The pull request introduces modifications to the SearchBar and Inbox components, focusing on how search parameters are managed in the URL. The SearchBar component now uses setSearchParams with a { replace: true } option, and a new useEffect hook manages the searchValue state based on URL parameters. The Inbox component similarly updates its handling of search parameters. Additionally, the test suite for the LoginPartyContext component has been revised to focus on the interaction between the search bar and navigation state.

Changes

File Path Change Summary
packages/frontend/src/components/Header/SearchBar.tsx Updated import to include useEffect, removed useNavigate, modified onSearch function to use setSearchParams with { replace: true }, added useEffect for managing searchValue.
packages/frontend/src/pages/Inbox/Inbox.tsx Modified setSearchParams to include an options object with { replace: true }, added comments for biome-ignore directives to control dependencies in useEffect.
packages/frontend/tests/stories/loginPartyContext.spec.ts Revised test for the "Go-back button" to check if it deletes the search bar value instead of updating state; removed several assertions related to button visibility.

Possibly related PRs

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: 2

🧹 Outside diff range and nitpick comments (3)
packages/frontend/src/components/Header/SearchBar.tsx (1)

Line range hint 15-21: Consider centralizing search state management

The component currently manages search state in multiple places:

  • URL parameters via useSearchParams
  • Global state via useSearchString
  • Local state via useState

This could lead to synchronization issues and makes the code harder to maintain.

Consider using a single source of truth for search state, preferably URL parameters, and derive other states from it. This would simplify the logic and make the component more maintainable.

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

119-129: Consider expanding test coverage for browser navigation.

The current test effectively verifies the basic back navigation flow. However, to ensure robust handling of browser history:

  1. Consider adding tests for:
    • Forward navigation after going back
    • Multiple back/forward navigations
    • History stack depth verification
  2. Verify that multiple searches don't create duplicate history entries

Example test cases to consider:

// Test forward navigation
await page.goBack();
await page.goForward();
searchParams = new URL(page.url()).searchParams;
expect(searchParams.has('search')).toBe(true);
expect(searchParams.get('search')).toBe('skatten din');

// Test multiple searches
await page.getByPlaceholder('Søk i innboks').fill('new search');
await page.getByPlaceholder('Søk i innboks').press('Enter');
await page.goBack();
searchParams = new URL(page.url()).searchParams;
expect(searchParams.get('search')).toBe('skatten din');
packages/frontend/src/pages/Inbox/Inbox.tsx (1)

138-141: Consider consistent URL parameter handling across all updates.

While this change correctly handles sort order updates, there are other places in the component where URL parameters are modified:

  • Filter changes (via FilterBar)
  • Search string updates
  • Initial parameter loading

Consider applying the same { replace: true } pattern to these updates to maintain consistent history behavior.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 84a7504 and 03961df.

📒 Files selected for processing (3)
  • packages/frontend/src/components/Header/SearchBar.tsx (2 hunks)
  • packages/frontend/src/pages/Inbox/Inbox.tsx (1 hunks)
  • packages/frontend/tests/stories/loginPartyContext.spec.ts (1 hunks)
🔇 Additional comments (3)
packages/frontend/src/components/Header/SearchBar.tsx (2)

3-3: LGTM! Import changes align with PR objective

The removal of useNavigate and addition of useEffect support the goal of improving browser history management.

Also applies to: 5-5


44-44: LGTM! Correct implementation to prevent history stack growth

The addition of { replace: true } is the key fix that prevents multiple history entries by replacing the current history state instead of pushing a new one.

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

113-117: LGTM! Clear test setup and naming.

The test setup is well-structured and the name accurately reflects its purpose of verifying search bar behavior with browser navigation.

Comment on lines +47 to +54
useEffect(() => {
const searchBarParam = new URLSearchParams(searchParams);
if (searchBarParam.get('search')) {
return;
}
setSearchValue('');
searchBarParam.delete('search');
}, [location.search]);
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

⚠️ Potential issue

Fix useEffect dependencies and add missing import

The review comment was correct about the implementation issues. Looking at the file content:

  1. location is not imported but used in dependency array
  2. The component only imports useSearchParams from 'react-router-dom'
  3. The effect should use searchParams in the dependency array since that's what it's actually using

Apply this fix:

- }, [location.search]);
+ }, [searchParams]);

The current implementation is problematic because:

  • It references an undefined location variable
  • The actual data being used (searchParams) is not in the dependency array
  • The effect's logic is already correctly working with searchParams, making location.search unnecessary
🔗 Analysis chain

Fix useEffect implementation issues

There are several issues with the current useEffect implementation:

  1. location.search is used in dependency array but not imported/defined
  2. searchParams should be in the dependency array since it's used in the effect
  3. The effect might cause unnecessary state updates when URL changes

Apply this fix:

  useEffect(() => {
    const searchBarParam = new URLSearchParams(searchParams);
    if (searchBarParam.get('search')) {
      return;
    }
    setSearchValue('');
    searchBarParam.delete('search');
-  }, [location.search]);
+  }, [searchParams]);

Let's verify if location is properly imported elsewhere:


The previous command failed due to typescript extension issue. Let's try a broader search and also look at the actual file content to understand how location is being used and if there are any imports we might have missed.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if location is imported from react-router-dom
rg "import.*location.*from 'react-router-dom'" --type typescript

Length of output: 107


Script:

#!/bin/bash
# Check if location is imported from react-router-dom with broader search
rg "import.*location.*from ['\"]react-router-dom['\"]"

# Also check for useLocation hook usage
rg "useLocation"

# Check the actual file content to understand the context better
cat "packages/frontend/src/components/Header/SearchBar.tsx"

Length of output: 4917

@@ -136,7 +136,7 @@ export const Inbox = ({ viewType }: InboxProps) => {
useEffect(() => {
const newSearchParams = new URLSearchParams(searchParams);
newSearchParams.set('sortBy', selectedSortOrder);
setSearchParams(newSearchParams);
setSearchParams(newSearchParams, { replace: true });
Copy link

@coderabbitai coderabbitai bot Nov 8, 2024

Choose a reason for hiding this comment

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

💡 Codebase verification

Most setSearchParams calls already use { replace: true }, but one in SearchBar needs attention

Found one instance in packages/frontend/src/components/Header/SearchBar.tsx that doesn't use the replace option:

  • Line: setSearchParams(newSearchParams); when clearing search data

All other instances already properly use { replace: true }:

  • In useParties.ts: All three calls use { replace: true }
  • In SearchBar.tsx: Search value update uses { replace: true }
  • In Inbox.tsx: Sort order update uses { replace: true }
🔗 Analysis chain

LGTM! Prevents duplicate history entries for sort order changes.

The addition of { replace: true } to setSearchParams correctly prevents new history entries when changing sort order, aligning with the PR's objective.

Let's verify other URL parameter updates in the codebase:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for other setSearchParams calls that might need similar treatment

# Search for setSearchParams calls without replace option
rg "setSearchParams\([^)]*\)" --type ts --type tsx -A 2 -B 2

Length of output: 90


Script:

#!/bin/bash
# Let's try a different approach using ripgrep without file type filters
# and then filter results in post-processing

# Search for setSearchParams calls
rg "setSearchParams\(" -A 2 -B 2

Length of output: 2372

Copy link
Contributor Author

Choose a reason for hiding this comment

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

TY rabbit!

Copy link

Choose a reason for hiding this comment

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

@mbacherycz You're welcome!

/(=^ x ^=)\

@mbacherycz mbacherycz force-pushed the fix/avoid_multiple_browser_history_push branch 2 times, most recently from 53c2338 to b7731f1 Compare November 8, 2024 12:12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
dev developer task
Projects
None yet
Development

Successfully merging this pull request may close these issues.

fix: browser history should not include double entries
2 participants