-
Is there an example of how this can be used together with I have multiple I have a lot of code, but am unsure if it's the correct way of doing things: const searchParams = useSearchParams();
const router = useRouter();
const pathname = usePathname();
const [selectedFormats, setSelectedFormats] = useQueryState(
'format',
parseAsArrayOf(parseAsString).withDefault([])
);
const handleToggle = (format: string[]) => {
setSelectedFormats(format.length > 0 ? format : null);
let updatedSearchParams = new URLSearchParams(searchParams.toString());
if (format.length > 0) {
updatedSearchParams.set('format', format.join(','));
} else {
updatedSearchParams.delete('format');
}
router.push(`${pathname}?${updatedSearchParams.toString().replace(/%2C/g, ',')}`);
}; It feels a bit much, is there a neater way of doing things? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
There are a couple of ways First is the const [selectedFormats, setSelectedFormats] = useQueryState(
'format',
parseAsArrayOf(parseAsString)
.withDefault([])
.withOptions({
shallow: false, // Send updates to the server
history: 'push' // And push a new entry in the History API while doing so
})
);
const handleToggle = (format: string[]) => {
setSelectedFormats(format.length > 0 ? format : null);
}; This might work fine for one low-frequency state, but you mention multiple states, potentially high-frequency (text input), for which I wouldn't recommend this approach (the Back button would undo a bunch of characters at a time, horrible UX). I might need to know more about your use-case to help you further on this point. |
Beta Was this translation helpful? Give feedback.
There are a couple of ways
nuqs
can help you here.First is the
history
option, that can tellnuqs
to push a new entry in the History. Combine it withshallow: false
to use the Next.js router to send an update to the server, and you get the same behaviour as your example:This might w…