@spa-tools/interaction-hooks
useQueryState()
Have you ever needed to interact with the browser URL's querystring values and even update them without triggering hard reloads?
Maybe your users want to bookmark a view with a particular filter-set they've defined? Or maybe you want to remember the sort column/direction settings a user last selected for a view? So many scenarios, if only it wasn't a pain, right?
Pain no more! The useQueryState<S>
hook is here to save the day!
The generic S
type is used to define the shape of the query state object.
Usage
import { useQueryState } from '@spa-tools/interaction-hooks';
// here we edefine the shape for our query state
interface SortColumnInfo {
sortColumn: string;
sortDirection: 'ASC' | 'DESC';
}
function UseQueryStateExample() {
// we pass true to the useQueryState hook to enable the cache (i.e. localStorage)
// feature so that the query state for this view is remembered across page reloads
const { queryState, setQueryState } = useQueryState<SortColumnInfo>(true);
return (
<div>
<div>
<button
onClick={() => {
// here we set the query state to sort by age in descending order
setQueryState({ sortColumn: 'age', sortDirection: 'DESC' });
}}
>
Sort by Age (DESC)
</button>
<button
onClick={() => {
// here we set the query state to sort by name in ascending order
setQueryState({ sortColumn: 'name', sortDirection: 'ASC' });
}}
>
Sort by Name (ASC)
</button>
<button
onClick={() => {
// here we hard reload the page with querystring removed
// to test the cache feature
window.location.href = window.location.href.split('?')[0];
}}
>
Hard reload to test cache
</button>
<button
onClick={() => {
// here we clear the query state
setQueryState(null);
}}
>
Clear sort settings
</button>
</div>
<div>
{queryState === null ? (
`Click one of the "Sort by" buttons and watch the browser's URL and also how this text changes!`
) : (
<span>
Sort column <strong>{queryState.sortColumn}</strong> in <em>{queryState.sortDirection}</em> direction!
</span>
)}
</div>
</div>
);
}
Parameters
Name | Type | Required? | Default | Description |
---|---|---|---|---|
useLocalStorage | boolean | no | false | If true localStorage will be used so that the query state will be cached using current browser URL as the state key |
Returns
Returns a UseQueryStateResult
object.
UseQueryStateResult
UseQueryStateResult<S>
is the object returned from the useQueryState
hook.
Prop | Type | Comments |
---|---|---|
queryState | S | The current query state that is auto-parsed from the browser URL |
setQueryState | (newQueryState: S | null) => void | Function used to modify the URL's query state |