router icon indicating copy to clipboard operation
router copied to clipboard

useMatch doesn't update `match.search`

Open enisdenjo opened this issue 3 years ago • 3 comments
trafficstars

Describe the bug

Whenever the search params in the URL change, the const match = useMatch() hook re-renders but does not update the match.search.

Not sure if this behaviour is intentional, but feels wrong mainly because the useMatch hook causes a re-render but provides stale search params.

Your Example Website or App

https://stackblitz.com/edit/react-location-usematch-vs-usesearch?file=UsingMatch.tsx

Steps to Reproduce the Bug or Issue

  1. const match = useMatch()
  2. expect(match.search).toEqual({ counter: 0 })
  3. navigate({ search: ++counter })
  4. useMatch causes a re-render
  5. expect(match.search).toEqual({ counter: 1 }), actual { counter: 0 }

Expected behavior

Whenever the search params in the URL change, the const match = useMatch() hook re-renders and provides the up-to-date match.search.

Screenshots or Videos

No response

Platform

  • OS: macOS
  • Browser: Chrome
  • Version: 100.0.4896.60

Additional context

No response

enisdenjo avatar Apr 07 '22 11:04 enisdenjo

useSearch does give the expected result by the way.

DiederikvandenB avatar Apr 10 '22 10:04 DiederikvandenB

useSearch does give the expected result by the way.

Thank you so much. I was about to switch back to react-router. The documentation is hard to follow

vivian940425 avatar May 30 '22 08:05 vivian940425

@xstmjh In that case, check this out: https://github.com/TanStack/react-location/issues/255#issuecomment-1117936631

DiederikvandenB avatar May 30 '22 13:05 DiederikvandenB

We're also running into this issue when trying to migrate from React Router to React Location. Ideally, I don't want to have to use useSearch in addition to useMatch if a route contains both route and search parameters; I'd like to be able to access them both from one hook.

I have noticed that the documentation doesn't explicitly mention using useMatch to access search parameters. However, I use TypeScript as a form of documentation and useMatch looks like it's supposed to return search parameters (which to be exhaustive, it does, but it doesn't appear to update them).

@tannerlinsley if useMatch is designed/intended to return up-to-date search parameters, should this be fixed? If not, should the useMatch return type be updated to remove search parameters? Alternatively, are we using the APIs incorrectly and are the search parameters purposefully exposed from useMatch for a reason that we're not aware of?

Thanks for the great open-source libraries 🙂

louis-young avatar Oct 18 '22 15:10 louis-young

TanStack Router is doing search params in a unified way now with const { search } = router.useMatch()

tannerlinsley avatar Nov 10 '22 14:11 tannerlinsley