New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

kit-state-params

Package Overview
Dependencies
Maintainers
0
Versions
20
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

kit-state-params

## 1. Introduction

  • 0.0.23
  • latest
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
19
decreased by-42.42%
Maintainers
0
Weekly downloads
 
Created
Source

kit-state-params

1. Introduction

kit-state-params is a lightweight query params state management library for SvelteKit that simplifies state management and URL synchronization. It provides a seamless way to keep your application state in sync with URL search parameters, enhancing user experience and enabling easy sharing of application states.

Key features:

  • Works like a normal state in svelte 5 : reactive, mutable and without using the boxed value pattern.
  • Automatic URL synchronization: State changes are reflected in the URL, making it easy to share and bookmark specific application states.
  • Handles string, number, date, boolean and enum as primitives, arrays of primitives, arrays of objects and nested objects.
  • Type safe and runtime safe: Define your state structure with a simple schema, ensuring type safety throughout your application.
  • Reactive state management: Utilizes Svelte's reactive state system for efficient updates and rendering.
  • Customizable debounce: Control the frequency of URL updates to optimize performance.
  • History management: Choose between pushing new history entries or replacing the current one.
  • Clean URL handling: Automatically removes empty values from the URL to keep it tidy.
  • Can preserve unknown params (not defined in the schema).

2. Installation

npm install kit-state-params
pnpm install kit-state-params
bun install kit-state-params

3. Client Side

Create a state with the searchParams function. You need to pass a schema of the parameters you want to use. The type of the state will be infered from the schema. The state is a like a normal state in svelte 5. It is reactive and you can mutate or update its properties.

Every mutation will be reflected in the url search params. You can use the debounce option to customize the time between each update.

Each update will trigger a navigation by default but you can use the shallow option to prevent it.

You can use the pushHistory option to control if you want to push a new history entry or replace the current one. By default it will not push a new history entry.

The library will try its best to keep the url clean by removing empty strings, null values and so on.

Basic usage

<script lang="ts">
	import { stateParams } from 'kit-state-params';

	const searchParams = stateParams({
		schema: {
			search: 'string',
			tags: ['number']
		}
	});
</script>

<button
	onclick={() => {
		searchParams.tags.push(searchParams.tags.length + 1);
	}}
>
	Add tag
</button>

<input bind:value={searchParams.search} />

{JSON.stringify(searchParams)}

Options

The stateParams function accepts an options object. Here's a table describing the available options:

NameTypeDescriptionDefault ValueRequiredExample
schemaSchemaDefines the structure and types of the URL parameterstrue{ search: 'string', tags: ["number"] }
debouncenumberTime in milliseconds to wait before updating the URL after a state change200false500
pushHistorybooleanWhether to push a new history entry on state changefalsefalsetrue
twoWayBindingbooleanEnables synchronization between URL changes and statetruefalsefalse
preserveUnknownParamsbooleanKeeps URL parameters not defined in the schematruefalsefalse
invalidateAllbooleanInvalidates the state and re-fetches all load functions on state changefalsefalsefalse
invalidate(string / URL)[]Other routes / load functions to invalidate on state change[]false["profile", "user"]
shallowbooleanIf true, will not trigger a navigation and therefore not rerun the current load functionfalsefalsetrue

Schemas

The schema is a simple object that defines the structure of the URL parameters. It is an object where the keys are the parameter names and the values are the types.

Primitive types are: string, number, date, boolean and enum.

You can define arrays of primitives and arrays of objects.

Objects can be nested and can be of any type.

Simple schema
const schema = {
	search: 'string',
	new: 'boolean',
	startDate: 'date',
	count: 'number',
	enum: '<blue,green,red>'
};
Schema with arrays and nested objects
const schema = {
	// Define an object with nested objects
	user: {
		language: '<en,fr,es>'
		name: 'string',
		address: {
			street: 'string',
			city: 'string',
			zip: 'string'
		}
	},
	// Define an array of strings (can be any other primitive: boolean, number, date)
	tags: ['string'],
	// Define an array of objects (objects inside arrays can also be nested)
	friends: [
		{
			name: 'string',
			age: 'number'
		}
	]
};
Extras

the stateParams function returns a proxy reflecting the defined schema that also contains:

  • a $reset function to clear the search params (it will also clear the unknown params in the url if you set preserveUnknownParams to false)
  • a $searchParams property that is the underlying SvelteURLSearchParams reactive URLSearchParams

4. Server Side

kit-state-params also exports a parseURL function. This function can be used to parse the URL parameters into a typed object. It can be usefull inside the load function of a route.

import { parseURL } from 'kit-state-params';
export const load = ({ url }) => {
	const searchParams = parseURL(url, {
		search: 'string',
		tags: ['number']
	});
	const result = await api.getCustomers({
		search: searchParams.search,
		// search is of type string | null
		tags: searchParams.tags
		// tags is of type number[]
	});
	return {
		result
	};
};

License

This project is licensed under the MIT License. This README provides a comprehensive introduction to your library, installation instructions, and usage examples covering the main functionalities. It also includes sections on advanced usage and error handling. You may want to adjust the project name, installation instructions, and license information to match your specific project details.

FAQs

Package last updated on 24 Oct 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc