import React from "react"
import { useParams, useLocation, useHistory, useRouteMatch } from "react-router-dom"
import qs from "qs"
const defaultOptions = {
ignoreQueryPrefix: true,
interpretNumericEntities: true
}
// Hook
export function useRouter(options = defaultOptions) {
const params = useParams()
const location = useLocation()
const history = useHistory()
const match = useRouteMatch()
// Return our custom router object
// Memoize so that a new object is only returned if something changes
return React.useMemo(() => {
const query = qs.parse(location.search, options)
return {
// For convenience add push(), replace(), pathname at top level
push: history.push,
replace: history.replace,
pathname: location.pathname,
query,
setQuery: (q, options = {}) => {
const { method = "push" } = options
const fn = typeof q === "function" ? q : query => ({ ...query, ...q })
const str = qs.stringify(fn(query))
history[method](`?${str}`)
},
params,
// Include match, location, history objects so we have
// access to extra React Router functionality if needed.
match,
location,
history
}
}, [params, match, location, history, options])
}
|