@kikobeats/use-query-state
v1.2.2
Published
React hook to set/retrieve state from URL query string
Downloads
135
Maintainers
Readme
use-query-state
React hook for sharing state via URL.
Installation
$ npm install @Kikobeats/use-query-state --save
Usage
Get query state
Just get it from window.location.search
const [query, setQuery] = useQueryState()
Pass a initial query state
This is especially useful for Server-side Rendering (SSR), when the initial query state will depends on the incoming request.
const [query, setQuery] = useQueryState(ssrQuery)
Transform the query state
Sometimes you want to modify the window.location.search
for anything you need for.
const safeDecode = value => {
try {
return decodeURIComponent(value)
} catch (_) {
return value
}
}
const [query, setQuery] = useQueryState(undefined, parsedQuery =>
Object.entries(parsedQuery).reduce((acc, [key, value]) => {
acc[key] = safeDecode(value)
return acc
}, {})
)
Integration
for Next.js
Since Next.js doesn't support ES Modules yet, you need to install next-transpile-modules
in order to make possible use the hook on Next.js:
const withTM = require('next-transpile-modules')(['@kikobeats/use-query-state'])
const nextConfig = {}
module.exports = withTM(withOffline(nextConfig))
for Gatsby
import useQueryState from '@kikobeats/use-query-state/gatsby'
License
use-query-state © Kiko Beats, released under the MIT License. Authored and maintained by Kiko Beats with help from contributors.
kikobeats.com · GitHub Kiko Beats · Twitter @Kikobeats