pbeshai / use-query-params

React Hook for managing state in URL query parameters with easy serialization.
https://pbeshai.github.io/use-query-params
ISC License
2.16k stars 96 forks source link

Query params namespaces #239

Closed doichev-kostia closed 2 years ago

doichev-kostia commented 2 years ago

Hey!

Could you tell me, please, whether it's possible to add some kind of namespace or prefix to the query params? This is useful in case we use the library for storing table pagination info, like offset, limit, searchText... However, what should we do in case there is more than 1 table on the page? I wonder if we could transform the params to something like this: ?documents:offset=10&documents:limit=25&reports:offset=0&reports:limit=15

Thank you in advance

pbeshai commented 2 years ago

Here are examples of three approaches that could work:

Example 1 - useQueryParam

const prefix = 'documents'
const [limit, setLimit] = useQueryParam(`${prefix}:limit`, NumberParam)

// ...

<button onClick={() => setLimit(35)}>Set limit ({limit})</button>

Example 2 - useQueryParams and destructure yourself

const prefix = 'documents'
const [query, setQuery] = useQueryParams({
  [`${prefix}:limit`]: NumberParam,
  [`${prefix}:offset`]: NumberParam,
})
const limit = query[`${prefix}:limit`]

// ...

<button onClick={() => setQuery({ [`${prefix}:limit`]: 35 })}>
  Set limit ({limit})
</button>

Example 3 - useQueryParams and a custom param that includes the prefix

const prefix = 'documents'

const { LimitParam, OffsetParam } = React.useMemo(() => {
  return {
    LimitParam: { ...NumberParam, urlName: `${prefix}:limit` },
    OffsetParam: { ...NumberParam, urlName: `${prefix}:offset` },
  }
}, [prefix])

const [{ limit, offset, ...other }, setQuery] = useQueryParams({
    limit: LimitParam,
    offset: OffsetParam,
  })

// ...

<button onClick={() => setQuery({ limit: 25 })}>Set limit ({limit})</button>
doichev-kostia commented 2 years ago

Wow, thanks