• Stars
    star
    490
  • Rank 89,811 (Top 2 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created about 2 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

The easiest way to read and WRITE from query parameters in sveltekit.

sveltekit-search-params

The fastest way to read AND WRITE from query search params in sveltekit.

Warning

This package is meant to be used with Svelte-Kit as the name suggest. Because it uses api that are only present in Svelte-Kit it will not work in your normal svelte project.

MIT License

npm bundle size

npm

npm

GitHub last commit

Contributing

Contributions are always welcome!

For the moment there's no code of conduct neither a contributing guideline but if you found a problem or have an idea feel free to open an issue

If you want the fastest way to open a PR try out Codeflow

Open in Codeflow

Authors

Installation

Install sveltekit-search-params with npm

  npm install sveltekit-search-params@latest -D

Usage/Examples

Simple case (single parameter)

The simplest and most effective way to use this library is by importing the method queryParam. You can invoke this method with a string that represent the search parameters you are looking for in the URL.

<script lang="ts">
    import { queryParam } from "sveltekit-search-params";

    const username = queryParam("username");
</script>

Your username is {$username}

the function returns a store so make sure to use it with the $ prepended to handle auto-subscriprion. In case there's not a query parameter with the chosen name it will simply be null.

Writing to the store (single parameter)

Reading query parameters is cool but you know what is even cooler? Writing query parameters! With this library you can treat your store just like normal state in svelte. To update the state and conseguentely the url you can just do this

<script lang="ts">
    import { queryParam } from "sveltekit-search-params";

    const username = queryParam("username");
</script>

Your username is {$username}
<input bind:value={$username} />

or if you prefer

<script lang="ts">
    import { queryParam } from "sveltekit-search-params";

    const username = queryParam("username");
</script>


Your username is {$username}
<input value={$username} on:input={(e)=>{
    $username = e.target.value;
}} />

Encoding and decoding

By default query parameters are strings but more often than not tho we are not working with strings. We are dealing with numbers, boolean, arrays and complex abjects. During the creation of the store you can specify an object containing an encode and a decode property that will be used to transform your data from and to the type you need.

<script lang="ts">
    import { queryParam } from "sveltekit-search-params";

    const count = queryParam("count", {
        encode: (value: number) => value.toString(),
        decode: (value: string | null) => value ? parseInt(value) : null,
    });
</script>

The count is {$count}
<input bind:value={$count} type="number"/>

this time $count would be of type number and the deconding function it's what's used to update the url when you write to the store.

Default values

Sometimes when we want to create a new variable we like to pass a default value. You can do this by passing a third field, defaultValue, in the second argument of the query param object.

<script lang="ts">
    import { queryParam } from "sveltekit-search-params";

    const count = queryParam("count", {
        encode: (value: number) => value.toString(),
        decode: (value: string | null) => value ? parseInt(value) : null,
        defaultValue: 10,
    });
</script>

The count is {$count}
<input bind:value={$count} type="number"/>

this will make the query parameter change as soon as the page is rendered on the browser (the query parameter will change only if it's not already present and only the first time the application render).

Warning

You can't run goto on the server so if the page is server side rendered it will still have the null value (this is to say don't relay on the assumption that the store will always be not null).

Helpers encodings and decodings

Write an encode and decode function may seem trivial but it's tedious for sure. sveltekit-search-params provide with a set of helpers for better readability and to avoid the hassle of writing common transforms. You can find those helpers exported in a ssp variable from the same package.

<script lang="ts">
    import { ssp, queryParam } from "sveltekit-search-params";

    const count = queryParam("count", ssp.number());
</script>

The count is {$count}
<input bind:value={$count} type="number"/>

this code will produce the same output as the code written above but far more readable and easier to read. You can find all the exports documented in the section ssp - Helpers.

You can also pass a default value to the function that will be the defaultValue of the object.

<script lang="ts">
    import { ssp, queryParam } from "sveltekit-search-params";

    const count = queryParam("count", ssp.number(10));
</script>

The count is {$count}
<input bind:value={$count} type="number"/>

Simple case (all parameters)

You can use the function queryParameters to get an object containing all the present search params.

<script lang="ts">
    import { queryParameters } from "sveltekit-search-params";

    const store = queryParameters();
</script>

<pre>
    {JSON.stringify($store, null, 2)}
</pre>

assuming the page is /?framework=svelte&isCool=true the above code will show

{
  "framework": "svelte",
  "isCool": "true"
}

by default all query parameters are string.

Writing to the store (all parameters)

Just like with the single parameter case you can just update the store and the URL at the same time by doing this

<script lang="ts">
    import { queryParameters } from "sveltekit-search-params";

    const store = queryParameters();
</script>

<pre>
    {JSON.stringify($store, null, 2)}
</pre>
<input value={$store.username} on:input={(e)=>{
    $store.username = e.target.value;
}} />

writing in the input will update the state and the URL at the same time.

Expecting some parameters

Most of the times if you need to read from query parameters you are expecting some parameters to be present. You can define the parameters you are expecting during the store creating and those will be merged with the actual query parameters despite the fact that they are present or not.

<script lang="ts">
    import { queryParameters } from "sveltekit-search-params";

    const store = queryParameters({
        username: true,
    });
</script>

<pre>
    {JSON.stringify($store, null, 2)}
</pre>

assuming the page is /?framework=svelte&isCool=true the above code will show

{
  "framework": "svelte",
  "isCool": "true",
  "username": null
}

if we add username to the URL like this /?framework=svelte&isCool=true&username=paoloricciuti we will get

{
  "framework": "svelte",
  "isCool": "true",
  "username": "paoloricciuti"
}

Encoding and Decoding

The parameter passed to queryParameters can aslo be used to specify the encoding and decoding just like the queryParam method.

<script lang="ts">
    import { queryParameters } from "sveltekit-search-params";

    const store = queryParameters({
        username: true,
        isCool: {
            encode: (booleanValue) => booleanValue.toString(),
            decode: (stringValue) => stringValue !== null && stringValue !== "false",
            defautValue: true,
        }
    });
</script>

<pre>
    {JSON.stringify($store, null, 2)}
</pre>

assuming the page is /?framework=svelte&isCool=true&username=paoloricciuti the above code will show

{
  "framework": "svelte",
  "isCool": true,
  "username": null
}

notice that this time isCool it's a boolean and not a string anymore. With this particular transformation we've assured that if the url is the following /?framework=svelte&isCool=false&username=paoloricciuti or if the isCool parameter is completely missing like this /?framework=svelte&username=paoloricciuti we will get

{
  "framework": "svelte",
  "isCool": false,
  "username": null
}

Helpers encodings and decodings

Obviously also in this case you can use the helpers functions provided inside ssp.

<script lang="ts">
    import { ssp, queryParameters } from "sveltekit-search-params";

    const store = queryParameters({
        username: true,
        isCool: ssp.boolean(true),
    });
</script>

<pre>
    {JSON.stringify($store, null, 2)}
</pre>

ssp - Helpers

There are six helpers all exported as functions on the object ssp. To each one of them you can pass a parameter that will be the default value for that query param.

object

To map from a query parameter to an object. An url like this /?obj={"isComplex":%20true,%20"nested":%20{"field":%20"value"}} will be mapped to

$store.obj.isComplex; //true
$store.obj.nested; // {field: "value"}
$store.obj.nested.value; // "value"

array

To map from a query parameter to an array. An url like this /?arr=[1,2,3,4] will be mapped to

$store.arr[0]; //1
$store.arr[1]; //2
$store.arr[2]; //3
$store.arr[3]; //4

number

To map from a query parameter to a number. An url like this /?num=1 will be mapped to

$store.num; //1

boolean

To map from a query parameter to a boolean. An url like this /?bool=true will be mapped to

$store.bool; //true

as we've seen an url like this /?bool=false will be mapped to

$store.bool; //false

just like an url like this /

string

This is exported mainly for readability since all query parameters are already strings.

lz

To map any JSON serializable state to his lz-string representation. This is a common way to store state in query parameters that will prevent the link to directly show the state.

An url like this /?state=N4IgbghgNgrgpiAXCAsgTwAQGMD2OoYCO8ATpgA4QkQC2cALnCSAL5A will map to

$store.state.value; //My cool query parameter

Store options

Both functions accept a configuration object that contains the following properties:

debounceHistory

The number of milliseconds to delay the writing of the history when the state changes. This is to avoid cluttering the history of the user especially when a store is bound to an input text (every keystroke would cause a new history entry). It defaults to 0. If set a new entry in the history will be added only after debounceHistory seconds of "inactivity".

pushHistory

A boolean defining if the history have to be written at all. If set to false no new history entries will be written to the history stack (the URL will still update but the user will not be able to go back with the browser).

How to use it

To set the configuration object you can pass it as a third parameter in case of queryParam or the second in case of queryParameters.

<script lang="ts">
    import { ssp, queryParameters, queryParam } from "sveltekit-search-params";
    const name = queryParam("name", ssp.string(), {
        debounceHistory: 500, //a new history entry will be created after 500ms of this store not changing
    });
    const count = queryParam("count", ssp.number(), {
        debounceHistory: 1500, //a new history entry will be created after 1500ms of this store not changing
    })
    const store = queryParameters({
        username: true,
        isCool: ssp.boolean(true),
    }, {
        pushHistory: false, //no new history entries for this store
    });
</script>

Vite dependecies error

If you ran into issues with vite you need to update your vite.config.ts or vite.config.js file to include the plugin exported from sveltekit-search-params/plugin. It's as simple as

import { sveltekit } from "@sveltejs/kit/vite";
import { ssp } from "sveltekit-search-params/plugin";

/** @type {import('vite').UserConfig} */
const config = {
  plugins: [ssp(), sveltekit()],
};

export default config;

Warning

This step is required if you are running on an old version of vite/sveltekit

More Repositories

1

sveltekit-view-transition

Start using view transitions without any hassle!
TypeScript
160
star
2

hexwords

Svelte
101
star
3

svelte-action-balancer

A svelte action to balance the text inside the an html node. Heavily inspired by react-wrap-balancer
Svelte
70
star
4

optimistikit

Optimistic UI in sveltekit made easy
TypeScript
53
star
5

svelte-client-components

Preprocessor for svelte that allows you to annotate a component as a client component with the extension `.client.svelte`
JavaScript
17
star
6

sveltekit-defer

Make use of server sent events to transfer Promises over the wire with sveltekit
TypeScript
15
star
7

sprinkle-js

JavaScript
14
star
8

svelte-typewriter-store

A custom store for svelte to easily get a typewriter effect.
TypeScript
11
star
9

veritabs

A SvelteKit webapp to calculate a table of truth and get a simplified boolean expression
Svelte
7
star
10

sveltekit-client-hints

Avoid Content Layout Shift with a custom implementation of Client Hints!
TypeScript
6
star
11

teleport-kit

teleport a value from the server to the client...even if it's random!
TypeScript
4
star
12

moviemojis

Guess the movie based on the emoji list
TypeScript
3
star
13

animotion-kit

SvelteKit version of Animotion
Svelte
2
star
14

sveltejs-kit-defer-test

Created with StackBlitz ⚡️
Svelte
2
star
15

jdsl

This repo is to save and share the work of our lord and savior Tom...which btw is a genious.
JavaScript
1
star
16

storybook-for-brittney

Svelte
1
star
17

use-state-with-callback

Public repository for the react hook useStateWithCallback
JavaScript
1
star
18

i-like-it-move-it-move-it

Svelte
1
star
19

rcc.lol

JavaScript
1
star
20

ricciuti.me

my personal website
Svelte
1
star
21

metl-types-repro

Svelte
1
star
22

paraglide-nested-structure

How to transform the functions from paraglide in a nested structure complete with TS, playwright
TypeScript
1
star
23

rn-classes

TypeScript
1
star
24

quiz-o-matic

JavaScript
1
star
25

test-stale-while-revalidate

Created with StackBlitz ⚡️
CSS
1
star
26

test-defer-remix

TypeScript
1
star
27

speedvent-of-code

A Sveltekit webapp to quickly spin up a project with the input from advent of code already loaded in
Svelte
1
star
28

sharable-state-slides

Slides for the talk "Sharable state"
Svelte
1
star
29

typescript-styleprops-bug

Minimal reproduction for the typescript language server of svelte
JavaScript
1
star