-
Hey, would you mind adding a function that would check against base params and return boolean depending on whether the current params are equal or not to the base ones? It would be useful especially if dev would like to show |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Here's an example: 'use client'
import { type inferParserType, parseAsFloat, type ParserMap, useQueryStates } from 'nuqs'
import { Suspense } from 'react'
export default function Page() {
return (
<Suspense>
<Client />
</Suspense>
)
}
const searchParams = {
lat: parseAsFloat.withDefault(0),
lng: parseAsFloat.withDefault(0)
}
function isDefaultState<Parsers extends ParserMap>(
parsers: Parsers,
values: inferParserType<Parsers>
): boolean {
for (const [key, parser] of Object.entries(parsers)) {
if (!parser.eq(values[key], parsers[key].defaultValue)) {
return false
}
}
return true
}
function Client() {
const [state, setState] = useQueryStates(searchParams)
const isDefault = isDefaultState(searchParams, state)
return (
<div>
<p>isDefault: {isDefault.toString()}</p>
<p>lat: {state.lat}</p>
<p>lng: {state.lng}</p>
<button
onClick={() =>
setState({
lat: Math.random() * 180 - 90,
lng: Math.random() * 360 - 180
})
}
>
Random coordinates
</button>
<button onClick={() => setState(null)}>Reset</button>
</div>
)
} The key is to use the
That's expected: parseAsBoolean returns (as the name implies) a boolean, and the default value is typed based on the parser underlying type. |
Beta Was this translation helpful? Give feedback.
Here's an example: