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

[Docs]: for useSearchParams, functional updates should be explained in more detail #11449

Open
YakovL opened this issue Apr 15, 2024 · 3 comments
Labels

Comments

@YakovL
Copy link

YakovL commented Apr 15, 2024

Describe what's incorrect/missing in the documentation

Looking at https://reactrouter.com/en/main/hooks/use-search-params, one may think that to update one param while keeping the others, one can do:

const [searchParams, setSearchParams] = useSearchParams()

//...
const setPageNumber = (pageNumber: number) => setSearchParams(params => ({ ...params, page: String(pageNumber) }))

to update just the page portion of the query. However, this doesn't work: it removes all the query params and sets just the the page portion. (not sure if this is a bug or an intended behavior)

To work around this, one has to do:

const setPageNumber = (pageNumber: number) => setSearchParams(params => {
  params.set('page', String(pageNumber))
  return params
})

I think this is not trivial, and hence should be documented (unless it's a bug, I'm using 6.22.3).

@YakovL YakovL added the docs label Apr 15, 2024
@kiliman
Copy link
Contributor

kiliman commented Apr 15, 2024

URLSearchParams is not a regular object, so you can't spread it like you normally would.

Instead, you need to convert the existing params into an object via Object.fromEntries()

const [searchParams, setSearchParams] = useSearchParams()

//...
const setPageNumber = (pageNumber: number) => 
  setSearchParams(params => ({ ...Object.fromEntries(params), page: String(pageNumber) }))

https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/URLSearchParams

@depoulo
Copy link

depoulo commented Apr 15, 2024

IMHO the bigger undocumented caveat is that any mutation of searchParams (the first array entry returned), e.g. searchParams.delete('page') has the side effect of actually changing the URL.

@YakovL
Copy link
Author

YakovL commented Apr 15, 2024

Yeah, both are relevant: the Object.fromEntries trick would be helpful there, and then an explanation of how to properly delete a param would be also useful. Is

setSearchParams(params => {
  const queryParams = Object.fromEntries(params)
  delete queryParams['page']
  return queryParams
})

sufficient to avoid side-effects?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants