Get, set and watch url query parameters without any dependencies.
This library makes use of the History API to modify the browser URL for best integration with SPAs.
By default, all updates take place using history.pushState, but every method that modifies parameters has the option to use history.replaceState instead. (See section 'Single parameters' for examples.)
Updates to parameter values are detected by extending history.pushState and history.replaceState and also listing to popstate events to detect URL modifications via history.back(), history.foward() and the like.
Watching changes of search parameters happens through callbacks. If you want to escape the callback hell you can just use @algoristic/tinyparams-async, that acts as a rxjs wrapper and adds convenient .observe() methods.
npm i @algoristic/tinyparamsimport { params } from '@algoristic/tinyparams';const foo: string | undefined = params('foo').getValue();params('foo').setValue('bar'); params('foo').setValue('bar', { updateMode: 'replace', // default 'push' });params('foo').remove(); // equals to params('foo').setValue(undefined);// url = '...?foo=bar' params('foo').onChange((newValue, oldValue) => { console.log(`old=${oldValue}, new=${newValue}`); }); params('foo').setValue('baz'); // console: 'old=bar, new=baz'Perform a callback on the current value when it changes. Unlinke .onChange the method .watch starts with the initial value and only passes the current value.
// url = '...?foo=bar' params('foo').watch((foo) => { console.log(foo); }); // console: 'bar' params('foo').setValue('baz'); // console: 'baz'Get a snapshot of the current state of all query parameters.
const { get, keys, values } = params.snapshot(); // get value from snapshot let value: string | undefined = get('foo'); // analogous to params('foo').getValue() // get all parameter keys let keys: string[] = keys(); // returns ['foo', ...] // get all parameter key-value pairs let values: { key: string; value: string }[] = values(); // returns [{ key: 'foo', value: 'bar' }, ...]Behaves similar to params(key).watch(...).
params.watch(({ get, keys, values }) => { keys = keys(); values = values(); ... });const { setOne, setMany, setAll } = params.modifiers(); // set one value setOne('foo', 'bar'); // analogous to `params('foo').setValue('bar')` // set many values (but retain existing other parameters) setMany({ foo: 'bar', answer: 42, debug: true }); // override all query parameters setAll({ foo: 'bar', answer: 42 });@algoristic/tinyparams is fully compatible with hash routing by just setting:
params.useHash = true;This library may seem irrelevant in the age of frameworks and incredibly good routing. But when first meeting JavaScript I wrote this abomination of a "library" for a personal project: https://github.com/algoristic/js-url-parameters.
I keep this project publically visible to remind myself of how not to write code. And I just needed to rewrite this to prove myself I can do better now.