parseAsSort
Parserparamsync > parsers

parseAsSort

Composite parser for tabular sort state, column sorting, and order direction.

TSTypeScript Signature
IntelliSense
parseAsSort<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 JSXLn 26, Col 1

Clean URL Behavior

The default sorting state is omitted from the URL to preserve canonical links.

State ConditionClean URL ActionResulting URL
sort === { field: "createdAt", order: "desc" } (defaults)Key removed from URLhttps://example.com/posts
sort === { field: "price", order: "asc" }Serialized as `?sort=price.asc`https://example.com/posts?sort=price.asc

Configuration Parameters

ParameterTypeDefaultDescription
defaultFieldstring-Baseline field to sort by (e.g. "createdAt", "name", "price").
defaultOrder"asc" | "desc""asc"Baseline order direction. Defaults to "asc".
separatorstring"."Delimiter between field and direction. Defaults to period `.`.

Related API References