Use an object input to useQueryState
#690
-
Often we define a handful parsers in a single part of our domain, and want to use them in multiple places throughout the codebase. When we then want to share them with a export const pageParser = parseAsInteger
export const parsers = {
page: pageParser,
size: parseAsInteger,
sort: parseAsCustomSortObject,
query: parseAsString
}
// callsite
const [page, setPage] = useQueryState("page", pageParser) Or: // searchParams.ts
export const PAGE_KEY = "page"
export const parsers = {
[PAGE_KEY]: parseAsInteger,
size: parseAsInteger,
sort: parseAsCustomSortObject,
query: parseAsString
}
// callsite
const [page, setPage] = useQueryState(PAGE_KEY, parsers[PAGE_KEY]) In both case I find this a little suboptimal, as we expand the exposed surface area of our interface with search params, so that we can use a single key. To me this feels a little leak-y. It also reduces traceability of usage throughout the codebase, as there are now multiple symbols we would need to search for references to, before we can understand how our interface is used. To get around these issues we've taken to using // searchParams.ts
export const parsers = {
page: parseAsInteger,
size: parseAsInteger,
sort: parseAsCustomSortObject,
query: parseAsString
}
// callsite
const [page, setPage] = useQueryState(pick(parsers, "page")) This way, we can keep a narrower surface area to our domain exposed, and keep tracability on a single symbol. Obviously there's an open question as to what should happen if an object with multiple keys is provided, which I think we can't enforce in the types? But potentially a runtime error could be raised? Or the first key be used? In any case, curious to hear if you think this would be beneficial! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
I agree. I've been thinking for a while that the two hooks should be merged into one, making the API simpler and easier to use. There's been a lot of layering of features in v1. v2 will bring adapters for other frameworks, but a good cleanup and rethinking of how to make this library scalable will be the focus for v3. We might not get to the level of DX given by TanStack Router, but getting at least 80% there for other routers is the end game. |
Beta Was this translation helpful? Give feedback.
I agree. I've been thinking for a while that the two hooks should be merged into one, making the API simpler and easier to use. There's been a lot of layering of features in v1. v2 will bring adapters for other frameworks, but a good cleanup and rethinking of how to make this library scalable will be the focus for v3.
We might not get to the level of DX given by TanStack Router, but getting at least 80% there for other routers is the end game.