npm package: @hotel-smarters/polyfill-search-params
Description: A polyfill for URL search parameters manipulation in browsers
Author: v.petrosyan
Latest version: 1.0.5

# Polyfill Search Params

A lightweight TypeScript library that provides a polyfill for URL search parameters manipulation in browsers. This library gives you a simple interface to get, set, and delete URL query parameters while maintaining browser history.

## Features

- ⚛️ **React Router Integration**: Works seamlessly with react-router-dom
- 🚫 **No useMemo Required**: Direct URLSearchParams API without React hooks overhead
- 🔄 **Automatic URL Sync**: Updates browser URL automatically via react-router navigation
- 🔒 **Type Safe**: Written in TypeScript with full type definitions
- 📋 **Full URLSearchParams API**: Complete compatibility with native URLSearchParams
- 🔄 **Iterator Support**: Full support for forEach, keys(), values(), entries()
- 🪶 **Lightweight**: Minimal footprint with only react-router-dom dependency
- 🌐 **Browser Compatible**: Works in all modern browsers
- 📦 **Multiple Formats**: Supports CommonJS, ESM, and UMD formats

## Installation

```bash
npm install @hotel-smarters/polyfill-search-params
```

or

```bash
yarn add @hotel-smarters/polyfill-search-params
```

## Usage

### Basic Usage

```typescript
import { usePolyfillSearchParams } from '@hotel-smarters/polyfill-search-params';

const searchParams = usePolyfillSearchParams();

// Get a parameter value
const userId = searchParams.get('userId'); // returns string | null

// Set a parameter
searchParams.set('userId', '123');
// URL becomes: ...?userId=123

// Delete a parameter
searchParams.delete('userId');
// Parameter is removed from URL

// Get all parameters as string
const queryString = searchParams.toString();
// returns: "param1=value1&param2=value2"
```

### React Router Integration (No useMemo needed!)

```typescript
import React, { useState } from 'react';
import { usePolyfillSearchParams, createSearchParams } from '@hotel-smarters/polyfill-search-params';

function SearchComponent() {
  const searchParams = usePolyfillSearchParams(); // Works with react-router-dom!
  const [query, setQuery] = useState(searchParams.get('q') || '');

  const handleSearch = (newQuery: string) => {
    setQuery(newQuery);
    if (newQuery) {
      searchParams.set('q', newQuery); // Automatically updates URL via react-router
    } else {
      searchParams.delete('q');
    }
  };

  return (
    <div>
      <input
        type="text"
        value={query}
        onChange={(e) => handleSearch(e.target.value)}
        placeholder="Search..."
      />
      
      {/* Full URLSearchParams API support */}
      <p>Current query: {searchParams.get('q') || 'none'}</p>
      <p>Total params: {searchParams.size}</p>
      <p>Has search: {searchParams.has('q') ? 'yes' : 'no'}</p>
      
      {/* Iteration support */}
      <ul>
        {Array.from(searchParams.entries()).map(([key, value], index) => (
          <li key={index}>{key}: {value}</li>
        ))}
      </ul>
    </div>
  );
}
```

### Multiple Parameters

```typescript
const searchParams = usePolyfillSearchParams();

// Set multiple parameters
searchParams.set('category', 'electronics');
searchParams.set('sort', 'price');
searchParams.set('page', '1');
// URL becomes: ...?category=electronics&sort=price&page=1

// Get parameters
const category = searchParams.get('category'); // "electronics"
const sort = searchParams.get('sort'); // "price"
const page = searchParams.get('page'); // "1"

// Remove a parameter
searchParams.delete('page');
// URL becomes: ...?category=electronics&sort=price
```

## API

### Hooks

#### `usePolyfillSearchParams(): PolyfillURLSearchParams`

The main hook for React Router integration. Returns a URLSearchParams instance that automatically syncs with react-router-dom navigation.

```typescript
const searchParams = usePolyfillSearchParams();
searchParams.set('page', '2'); // Automatically updates URL via react-router
```

#### `useSearchParams(): PolyfillURLSearchParams` 

Returns a read-only URLSearchParams instance from the current location. Does not update the URL when modified.

```typescript
const searchParams = useSearchParams();
const page = searchParams.get('page'); // Read current page
```

#### `createSearchParams(init): PolyfillURLSearchParams`

Utility function to create URLSearchParams from various inputs without any navigation integration.

```typescript
const params = createSearchParams('?q=search&category=books');
const params2 = createSearchParams({ q: 'search', category: 'books' });
const params3 = createSearchParams([['q', 'search'], ['category', 'books']]);
```

### URLSearchParams Methods

The `PolyfillURLSearchParams` class implements the complete URLSearchParams interface:

#### `get(key: string): string | null`

Retrieves the value of the specified parameter.

- **Parameters:**
  - `key`: The parameter name to retrieve
- **Returns:** The parameter value as a string, or `null` if not found

#### `set(key: string, value: string): void`

Sets a parameter with the given key and value. Updates the browser URL.

- **Parameters:**
  - `key`: The parameter name
  - `value`: The parameter value

#### `delete(key: string): void`

Removes the specified parameter from the URL.

- **Parameters:**
  - `key`: The parameter name to remove

#### `toString(): string`

Returns the current query string (without the leading `?`).

- **Returns:** The query string as a string

## Browser Support

This library works in all modern browsers that support:
- `window.location`
- `window.history.replaceState`
- `URLSearchParams` (for URL encoding/decoding)

## TypeScript

This library is written in TypeScript and includes type definitions. No additional `@types` packages are needed.

```typescript
interface SearchParams {
    get: (key: string) => string | null;
    set: (key: string, value: string) => void;
    delete: (key: string) => void;
    toString: () => string;
}
```

## Contributing

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add some amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## Changelog

### 1.0.0
- Initial release
- Basic search parameters manipulation
- TypeScript support
- Browser history integration