Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Another easy way to read and write from query parameters in sveltekit and svelte 5.

License

NotificationsYou must be signed in to change notification settings

beynar/kit-query-params

Repository files navigation

1. Introduction

kit-query-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.
  • Handlesstring,number,date,boolean andenum 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-query-params
pnpm install kit-query-params
bun install kit-query-params

3. Client Side

Create a state with the queryParams 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 thedebounce option to customize the time between each update.

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

You can use thepushHistory 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

<scriptlang="ts">import {queryParamsState }from'kit-query-params';const queryParams=queryParamsState({schema: {search:'string',tags: ['number']}});</script><buttononclick={()=> {queryParams.tags.push(queryParams.tags.length+1);}}>Add tag</button><inputbind:value={queryParams.search} />{JSON.stringify(queryParams)}

Options

ThequeryParamsState 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"] }
debouncenumber orfalseTime in milliseconds to wait before updating the URL after a state change. If false the url will be updated on each state change and you will want to use the $sync method to manually update it.200false500
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
defaultthe type of your schemaThe default value of the state. It will be used to initialize the state if no value is found in the urlundefinedfalse{ search: 'hello', tags: [1, 2] }
enforceDefaultbooleanIf true, will enforce the default value when a value is set to null or when the state is$reset. This led to removingnull from the types of the values defined in your defaultfalsefalsetrue

Schema

Note

The schema is not a validator per se. It will ensure that the type of the value is correct but it will also coerce the value to the correct type rather than throwing an error. For example, if the value is"12" and the type isnumber, it will be coerced to12. If the value can not be coerced, it will be set tonull.

This allows to never have invalid values in the state but also to preserve the schema structure.

Therefore the validation will never throw an error while keeping your app safe from invalid values.

I did that because of the nature of search params, they can be easily manipulated by users (that can lead to invalid values in the state) and they can also be stored and shared (they can be staled). In the event of a schema change I assumed that no one would want to throw an error or a 404 for a user just because he has an old url.

At runtime, when modifying the state, the library will check if the value is of the correct type. If not, it will coerce it to the correct type. If it can not be coerced, it will prevent the update.

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 andenum.

You can define arrays of primitives and arrays of objects.

Objects can be nested and can be of any type.

Simple schema

constschema={search:'string',new:'boolean',startDate:'date',count:'number',enum:'<blue,green,red>'};

Schema with arrays and nested objects

constschema={// Define an object with nested objectsuser:{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

thequeryParamsState 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 setpreserveUnknownParams tofalse)
  • a$queryParams property that is the underlyingSvelteURLqueryParams reactive URLqueryParams
  • a$sync method to manually update the url

4. Server Side

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

import{parseURL}from'kit-query-params';exportconstload=({ url})=>{constqueryParams=parseURL(url,{search:'string',tags:['number']});constresult=awaitapi.getCustomers({search:queryParams.search,// search is of type string | nulltags:queryParams.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.

About

Another easy way to read and write from query parameters in sveltekit and svelte 5.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp