SearchParam

Example

HYDRATION FLASH ?
HYDRATION FLASH ?

Example Source Code

Code

import { onMount } from "svelte";
import { writable } from "svelte/store";

export function createSearchParam(key: string, defaultValue: string) {
	const value = writable(
		new URL(window.location.toString()).searchParams.get(key) ??
			defaultValue,
	);

	const setter = (newValue: string) => {
		const url = new URL(window.location.toString());

		url.searchParams.set(key, newValue);
		history.pushState({}, "", url);

		value.set(newValue);
	};

	onMount(() => {
		const popstate = () => {
			value.set(
				new URL(window.location.toString()).searchParams.get(key) ??
					defaultValue,
			);
		};

		window.addEventListener("popstate", popstate);

		return () => {
			window.removeEventListener("popstate", popstate);
		};
	});

	return [value, setter] as const;
}

Usage

<script lang="ts">
	import { createSearchParam } from "@hooks/SvelteSearchParam.svelte";

	const SIZES = ["SMALL", "MEDIUM", "LARGE"] as const;

	const [paramSize, setParamSize] = createSearchParam("size", SIZES[0]);
</script>

<div>
	<select
		onchange={(event) => {
			setParamSize(event.currentTarget.value);
		}}
		value={$paramSize}
	>
		{#each SIZES as size (size)}
			<option value={size}>{size}</option>
		{/each}
	</select>
	<div>{$paramSize}</div>
</div>