UNPKG

use-url-sync

Version:

use-url-sync is a utility package that helps you sync your states to url without hassle

39 lines (38 loc) 1.85 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); /* eslint-disable @typescript-eslint/no-explicit-any */ const react_1 = require("react"); const qs_1 = __importDefault(require("qs")); const useUrlSync = ({ states, ignore = {}, onStatesUpdated = {} }, onUrlGenerated) => { react_1.useEffect(() => { const cleanedStates = {}; Object.keys(states).forEach(key => { const value = states[key]; const shouldIgnore = ignore[key] || false; // Set default to false in case undefined const shouldIgnoreState = typeof shouldIgnore === 'boolean' ? shouldIgnore : shouldIgnore(value); /* Checks for state's value validity */ if (typeof ignore[key] !== 'undefined' ? !shouldIgnoreState : value !== null && value !== undefined && value !== '') { /* Checks if this state has a read function */ const thisStateOnChange = onStatesUpdated[key]; if (thisStateOnChange) Object.assign(cleanedStates, { [key]: thisStateOnChange(value) }); else Object.assign(cleanedStates, { [key]: value }); } }); /* Parsing it to url string using 'qs' library */ const queryUrl = qs_1.default.stringify(cleanedStates); const nextPath = `${window.location.pathname}?${queryUrl}`; typeof onUrlGenerated === 'function' && onUrlGenerated(nextPath); }, [ignore, onStatesUpdated, onUrlGenerated, states]); }; exports.default = useUrlSync;