1.0.4 • Published 6 years ago
react-router-query-params-hook v1.0.4
react-router-query-params-hook
React Hook for React Router for De-/Serializing query params
Installation
npm install react-router-query-params-hook
Usage
First you have to create your actual useQueryParams
hook. react-router
only
returns a string for location.search
, though you have to provide your own functions
for de-/serializing the query string.
You can for example use qs
:
export const useQueryParams = useQueryParamsFactory(
(queryString) => qs.parse(queryString, { ignoreQueryPrefix: true }),
(params) => qs.stringify(params, { encode: true, addQueryPrefix: true })
);
Now your useQueryParams
hook is ready for use:
// The input value of deserializer is the output of `qs.parse` (or whatever you use)
const deserializer = (value) => ({
foo: value.foo ? Number.parseInt(value.foo) : undefined
});
// The return value of serializer is the input of `qs.stringify` (or whatever you use)
const serializer = (value) => ({
foo: value.foo ? value.foo.toString() : undefined
});
// if you don't want to use an additional serializer, you
// can just pass an identity function for de-/serializer:
// (value) => value
export const MyComponent: React.FunctionComponent<Props> = (props) => {
const [params, setParams] = useQueryParams(deserializer, serializer);
useEffect(() => {
console.log("Params Changed", params);
}, [params]);
return (
<>
Params: {JSON.stringify(params)}<br />
<button onClick={() => setParams({foo:42})}>Set Params</button>
</>
)
};
Options
You can call setParams
with an optional options object:
const [params, setParams] = useQueryParams(deserializer, serializer);
// When using `keepUrl` the Browser URL won't update
setParams(newParams, { keepUrl: true });
// When using `force` it will trigger a state change, even if old and new params are the same
setParams(newParams, { force: true });
// When using `push` it will push a new state to browser history, instead of replace (default)
setParams(newParams, { push: true });
Todo
merge
option