Thinking through `parse`-ing query parameters
nandorojo opened this issue · comments
One thing that's a bit confusing: if I do push({ pathname: '/artists/[slug]', query: { offer: 100, slug: 'djkhaled' })
, it creates /artists/djkhaled?offer=100
.
In that case, offer
is "100"
, which is a string.
Using the parse
function on useParam
, we can turn this into a number:
useParam('offer', { parse: Number, initial: 0 })
However, useParam
currently only runs the parse
function on web. The reason being, on web, we know query params will always start out as strings, whereas on Native, they might be sent as actual primitive values, since this is possible for people to do with navigate('artist', { offer: 100 })
.
In order to achieve the same parse
-ing on both native and web, you have to add the parse
option to your linking config, in addition to your useParam
hook.
In reality, this should be set only once: in your linking config. But there are a few issues with that:
useParam
is set up to expect you to parse within the hook, not from the linking config, and the types resemble that. It would require a refactor of this hook- If we want to define our query parameter
parse
only in thelinking
config (which would be ideal), then I need to figure out how React Navigation does this under the hood, and copy the same logic intouseParam
. This is probably doable, just a bit annoying.
On Web, it's harder to restrict users from giving you a messed up URL. A big reason that useParam
has the parse
function is to avoid people giving you bad states: offer=hello
when offer
should be a number.
On Native, this isn't as likely to happen, since people can't type a URL (unless they're deep linking, I guess, but that's a really rare case).
The ideal API: set parse
and stringify
in your linking config, and useParam
just knows what do to on Web.
In fact...it's possible we could just use the react-navigation
params on Web too. Maybe that would simplify all of this, rather than reading from nextRouter.query
.
The ideal API: set parse and stringify in your linking config, and useParam just knows what do to on Web.
In fact...it's possible we could just use the react-navigation params on Web too.
💯