Skip to content

Commit

Permalink
chore(ui): exports parseSearchParams (#10185)
Browse files Browse the repository at this point in the history
As pointed out in #10164, parsing a `where` query from search params is
not exactly straightforward. Internally we rely on the `qs` module for
this, but it comes with a couple small nuances that are undocumented,
like the need to stringify them and specify depth. To standardize this,
we use a `parseSearchParams` utility internally that accepts the
`URLSearchParams` object that the `useSearchParams()` hook returns from
`next/navigation`. This PR exports that function for reuse and adds
JSDocs accordingly. Usage looks something like this:

```tsx
'use client'
import { useSearchParams } from 'next/navigation'
import { parseSearchParams } from '@payloadcms/ui'

function MyComponent() {
  const searchParams = useSearchParams()
  const parsedSearchParams = parseSearchParams(searchParams)
}
```
  • Loading branch information
jacobsfletch authored Dec 26, 2024
1 parent a0d8131 commit 5d3b816
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
4 changes: 4 additions & 0 deletions packages/ui/src/exports/client/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -288,13 +288,17 @@ export {
type ListViewClientProps,
type ListViewSlots,
} from '../../views/List/index.js'

export type {
ListComponentClientProps,
ListComponentServerProps,
ListPreferences,
} from '../../views/List/types.js'

export type { ListHeaderProps } from '../../views/List/ListHeader/index.js'

export { DefaultEditView } from '../../views/Edit/index.js'
export { SetDocumentStepNav } from '../../views/Edit/SetDocumentStepNav/index.js'
export { SetDocumentTitle } from '../../views/Edit/SetDocumentTitle/index.js'

export { parseSearchParams } from '../../utilities/parseSearchParams.js'
12 changes: 10 additions & 2 deletions packages/ui/src/utilities/parseSearchParams.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,16 @@ import type { ReadonlyURLSearchParams } from 'next/navigation.js'

import * as qs from 'qs-esm'

export function parseSearchParams(params: ReadonlyURLSearchParams): qs.ParsedQs {
const search = params.toString()
/**
* A utility function to parse URLSearchParams into a ParsedQs object.
* This function is a wrapper around the `qs` library.
* In Next.js, the `useSearchParams()` hook from `next/navigation` returns a `URLSearchParams` object.
* This function can be used to parse that object into a more usable format.
* @param {ReadonlyURLSearchParams} searchParams - The URLSearchParams object to parse.
* @returns {qs.ParsedQs} - The parsed query string object.
*/
export function parseSearchParams(searchParams: ReadonlyURLSearchParams): qs.ParsedQs {
const search = searchParams.toString()

return qs.parse(search, {
depth: 10,
Expand Down

0 comments on commit 5d3b816

Please sign in to comment.