Persisting Search Params with LocalStorage #604
leonardolombardi07
started this conversation in
Show and tell
Replies: 1 comment
-
Thanks for sharing! Doesn't the localStorage double up with the URL to "persist state across page reloads" ? To make sure search params are persisted when clicking a You could combine it with import Link from 'next/link'
import {
createSerializer,
parseAsBoolean,
parseAsString,
useQueryStates
} from 'nuqs'
type Page = 'a' | 'b'
type ClientProps = {
page: Page
target: Page
}
const searchParams = {
q: parseAsString.withDefault(''),
checked: parseAsBoolean.withDefault(false)
}
const serialize = createSerializer(searchParams)
export function Client({ page, target }: ClientProps) {
const [{ q, checked }, setParams] = useQueryStates(searchParams)
const href = serialize(`/app/persist-across-navigation/${target}`, {
q,
checked
})
return (
<>
<h1>Page {page}</h1>
<input
type="text"
value={q}
onChange={e => setParams({ q: e.target.value })}
/>
<input
type="checkbox"
checked={checked}
onChange={e => setParams({ checked: e.target.checked })}
/>
<Link href={href}>Go to page {target}</Link>
</>
)
} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hey everyone,
I wanted to share a snippet of code I built to persist search parameters using
localStorage
. I know it's kind of an easy task and a bit outside the scope ofnuqs
, but I thought it might be useful for others who want to maintain state across page navigation.The Setup
I'm using
nuqs
for query state management andusehooks-ts
forlocalStorage
. Here’s how I’ve combined them:Beta Was this translation helpful? Give feedback.
All reactions