All files / src/hooks useRouter.js

100% Statements 13/13
100% Branches 5/5
100% Functions 4/4
100% Lines 12/12
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41        2x           3x 3x 3x 3x       3x 3x 3x             2x 2x 2x 2x                      
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])
}