How to construct a URL that can store multiple values of a query param
Unanswered
Siamese Crocodile posted this in #help-forum
Siamese CrocodileOP
I am using query params to store the value of the selected checkboxes But I'm only able to store one value of a query param and if I try to store the other value, it replaces the values of that query param with the new value. I want my url looks something like this:
But in current behaviour, it updates the values of
My Code:
https://myapp.com/?s=6432bc97cbde9,64bd7707c0397edaBut in current behaviour, it updates the values of
s instead of appending the new value.My Code:
"use client";
const MyComponent = ({ title, options, initialFacets }) => {
const searchParams = useSearchParams();
const router = useRouter();
const titleName = title.toLowerCase();
const selectedFilter = searchParams.get(titleName);
const toggleOption = (optionValue) => {
const optionUrl = `/?${createQueryString(
searchParams,
titleName,
optionValue
)}`;
router.replace(optionUrl, { scroll: false });
};
return (
<CommandGroup>
{options.map((option) => {
return (
<CommandItem
key={option.value}
onSelect={() => toggleOption(option.value)}
className="cursor-pointer"
>
<div
className={cn(
"mr-2 flex h-4 w-4 items-center justify-center rounded-sm border border-primary",
selectedFilter === option.value
? "bg-primary text-primary-foreground"
: "opacity-50 [&_svg]:invisible"
)}
>
<CheckIcon className={cn("h-4 w-4")} />
</div>
</CommandItem>
);
})}
</CommandGroup>
);
};2 Replies
Siamese CrocodileOP
createQueryString code:
export function createQueryString(searchParams, name, value) {
const params = new URLSearchParams(searchParams)
params.set(name, value)
return params.toString()
}Use append() instead