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

Use `+` instead of `%20` to encode space in `StringParam` #185

Closed rijkvanzanten closed 3 years ago

rijkvanzanten commented 3 years ago

Is it possible to use a + instead of a %20 to encode spaces in the query param? I would like to match the query param generated by a regular HTML <form> (which by default relies on application/x-www-form-urlencoded and therefore +) for consistencies sake.

For example:

<form action="/search">
  <label>
    Search
    <input type="search" name="q" />
  </label>
</form>

with search query use query params

Will open localhost:3000/search?q=use+query+params where useQueryParam will force it to localhost:3000/search?q=use%20query%20params.

(I am aware that both are technically valid, and that the URL standards are finicky/messy. This is not a question of what should be used, but a question on how to have useQueryParam interop consistently with "regular" html 😁 )

pbeshai commented 3 years ago

I believe you should be able to accomplish this via the transformSearchString option... maybe something like...


function transformSearchStringPlusSpace(searchString) {
  return searchString.replaceAll('%20', '+');
}

const stringifyOptions = {
   transformSearchString: transformSearchStringPlusSpace,
}

<QueryParamProvider ReactRouterRoute={Route} stringifyOptions={stringifyOptions}>
  <App />
</QueryParamProvider>
rijkvanzanten commented 3 years ago

Thanks!

I didn't see any mention of QueryParamProvider in the readme/docs. How would one apply that idea to the usage examples found elsewhere?

For example in the following barebones usage of this library:

import { useQueryParam, StringParam } from 'use-query-params';

const MyComponent = () => {
  const [foo, setFoo] = useQueryParam('foo', StringParam);

  return <div>{foo}</div>
}
pbeshai commented 3 years ago

The QueryParamProvider is mentioned several places throughout the readme and the library will not work properly without it. Please refer to the Installation section to make sure you have it setup correctly.

rijkvanzanten commented 3 years ago

Ah gotcha. I was mistaken with the monorepos readme and the website (https://pbeshai.github.io/use-query-params/) which don't seem to mention any installation instructions.

I'm relying on a third party package to inject this lib in Gatsby (gatsby-plugin-use-query-params) which abstracts that Provider away, so it seemingly worked "without" me adding any providers manually. Seeing that that particular abstraction doesn't have any configuration options, this solution unfortunately isn't accessible without forking/updating that other lib. Oh well! Thanks for the info and have a good one 👍🏻