1.0.7 ā€¢ Published 12 months ago

@davstack/use-url v1.0.7

Weekly downloads
-
License
ISC
Repository
-
Last release
12 months ago

NPM Continuous Integration

Features

  • šŸŒ Simplified global state management: the URL serves as the single source of truth.
  • šŸ”— Supports Arrays, Objects, Arrays of Objects, Dates, and primitive data types.
  • šŸŸ¦ Supports TypeScript, with custom param types.

Installation

npm install @davstack/use-url

or

pnpm add @davstack/use-url

or

yarn add @davstack/use-url

Usage

import { useUrl } from '@davstack/use-url';

export default () => {
	const { params, setParam } = useUrl();
	const { name } = params;

	return (
		<>
			<h1>Hello, {name || 'anonymous visitor'}!</h1>
			<input value={name || ''}
				onChange={()=>setParam('name', e.target.value))}
			 />
			<button
				onClick={() => setParam('name', null)}
			>
			Clear
			</button>
		</>
	);
};

Example: simple counter stored in the URL:

import React from 'react';
import { useUrl } from '@davstack/use-url';

export default function CounterComponent() {
	const { params, setParam } = useUrl();

	const handleReset = () => setParam('count', 0);
	const handleIncrement = () => setParam('count', (c) => c ?? 0 + 1);
	const handleDecrement = () => setParam('count', (c) => c ?? 0 - 1);
	const handleClear = () => setParam('count', null);

	return (
		<>
			<pre>count: {count ?? 'Not set'}</pre>
			<button onClick={handleReset}>Reset</button>
			<button onClick={handleIncrement}>+</button>
			<button onClick={handleDecrement}>-</button>
			<button onClick={handleClear}>Clear</button>
		</>
	);
}

Types

import { Params } from '@davstack/use-url';

declare module '@davstack/use-url' {
	export interface Params {
		startDate: Date;
		endDate: Date;
		//... add custom properties here
	}
}

Caveats

Because the Next.js router is not available in an SSR context, this hook will always return null (or the default value if supplied) on SSR/SSG.

1.0.7

12 months ago

1.0.6

12 months ago

1.0.5

12 months ago

1.0.4

12 months ago

1.0.2

12 months ago

1.0.1

12 months ago

1.0.0

12 months ago