@toshick/querykeeper
v0.1.0
Published
Type-safe URL query state management for web applications
Maintainers
Readme
querykeeper
Type-safe URL query state management for web applications.
Define a schema, read typed values from the URL, update state, and sync with history.pushState / replaceState.
Install
npm install @toshick/querykeeperQuick start
import { bindToLocation, defineSchema, enumField, number, string } from "@toshick/querykeeper";
const schema = defineSchema({
page: number(1),
sort: string("name"),
order: enumField(["asc", "desc"], "asc"),
});
const { keeper } = bindToLocation({ schema });
keeper.get("page"); // number
keeper.setAndReplaceUrl("page", 2);
keeper.pushUrl({ pathname: "/items" });Schema fields
| Helper | Type | Example |
| --- | --- | --- |
| string(default?) | string | string("hello") |
| number(default?) | number | number(1) |
| boolean(default?) | boolean | boolean(false) |
| array("string" \| "number", default?) | string[] / number[] | array("string") |
| enumField(values, default?) | union of literals | enumField(["asc", "desc"], "asc") |
Default values are omitted from the query string. Unknown query parameters are preserved by default.
API
createQueryKeeper(options) / new QueryKeeper(options)
Create a keeper from a schema and optional initial search string.
const keeper = createQueryKeeper({
schema,
search: "?page=3",
preserveUnknownParams: true, // default: true
});bindToLocation(options)
Creates a keeper and listens to popstate to sync from the URL.
const { keeper, unsubscribe } = bindToLocation({
schema,
syncOnPopState: true, // default: true
});State updates
get(key)/getAll()— read current valuesset(key, value)/setAll(partial)— update in memorysetAndReplaceUrl(key, value)/setAllAndReplaceUrl(partial)— update andhistory.replaceStatepushUrl({ pathname?, hash? })— push current query to historyreplaceUrl({ pathname?, hash? })— replace current URLsyncFromSearch(search?)— reload from URLsubscribe(listener)— listen for changes
License
MIT
