Parserparamsync > parsers
parseAsSort
Composite parser for tabular sort state, column sorting, and order direction.
TSTypeScript Signature
IntelliSenseparseAsSort<TField extends string>(defaultField: TField, defaultOrder?: "asc" | "desc", separator?: string): ParserWithDefault<SortOption<TField>>What it does
Encodes `{ field, order }` configurations into standard query formats like `?sort=createdAt.desc` or `?sort=price.asc`. Automatically cleans the query string when set to the default sort order.
Best For
- Data grid table header click sorting
- E-commerce product feed sorting (Price: Low to High)
- Blog post and documentation chronological order
- Search relevance versus date toggling
How to use it properly
Import parseAsSort from 'paramsync' and bind it to useQueryState:
TSExample.tsx
'use client'; import { useQueryState, parseAsSort } from 'paramsync'; export function SortDropdown() { const [sort, setSort] = useQueryState( 'sort', parseAsSort('createdAt', 'desc') ); return ( <select value={`${sort.field}.${sort.order}`} onChange={(e) => { const [field, order] = e.target.value.split('.') as [string, 'asc' | 'desc']; setSort({ field, order }); }} className="bg-zinc-900 border border-zinc-800 text-zinc-200 text-sm rounded px-3 py-1.5" > <option value="createdAt.desc">Newest First</option> <option value="createdAt.asc">Oldest First</option> <option value="price.asc">Price: Low to High</option> <option value="price.desc">Price: High to Low</option> </select> );}main|paramsync
TypeScript JSX|UTF-8|Ln 26, Col 1
Clean URL Behavior
The default sorting state is omitted from the URL to preserve canonical links.
| State Condition | Clean URL Action | Resulting URL |
|---|---|---|
| sort === { field: "createdAt", order: "desc" } (defaults) | Key removed from URL | https://example.com/posts |
| sort === { field: "price", order: "asc" } | Serialized as `?sort=price.asc` | https://example.com/posts?sort=price.asc |
Configuration Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| defaultField | string | - | Baseline field to sort by (e.g. "createdAt", "name", "price"). |
| defaultOrder | "asc" | "desc" | "asc" | Baseline order direction. Defaults to "asc". |
| separator | string | "." | Delimiter between field and direction. Defaults to period `.`. |