UNPKG

beautiful-react-hooks

Version:

A collection of beautiful (and hopefully useful) React hooks to speed-up your components and hooks development

41 lines (40 loc) 1.54 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); var react_1 = require("react"); var react_router_dom_1 = require("react-router-dom"); var useDidMount_1 = __importDefault(require("./useDidMount")); var useURLSearchParams_1 = __importDefault(require("./useURLSearchParams")); /** * Ease the process of modify the query string in the URL for the current location. */ var useQueryParam = function (key, options) { if (options === void 0) { options = {}; } var history = (0, react_router_dom_1.useHistory)(); var params = (0, useURLSearchParams_1.default)(); var initialisedRef = (0, react_1.useRef)(false); var onMount = (0, useDidMount_1.default)(); var setParam = (0, react_1.useCallback)(function (nextValue) { if (!nextValue) { params.delete(key); } else { params.set(key, nextValue); } if (options.replaceState) { history.replace({ search: params.toString() }); return; } history.push({ search: params.toString() }); }, [options.replaceState, history]); onMount(function () { if (!params.has(key)) { initialisedRef.current = true; setParam(options.initialValue); } }); return [initialisedRef.current ? params.get(key) : options.initialValue, setParam]; }; exports.default = useQueryParam;