-
On the project i had a requirement of working with Sets. I'm using react aria and it internally uses Sets to store collection state. So since i did not want to convert from array to Set everywhere in the app I created a set Parser to use for nuqs. Maybe somebody might find this useful if included by default. This is what i wrote: export function parseAsSetOf<ItemType>(itemParser: Parser<ItemType>, separator = ",") {
const encodedSeparator = encodeURIComponent(separator);
return createParser({
parse: query => {
if (query === "") return new Set() as Set<ItemType>;
let parsedSet = new Set<ItemType>();
let splitQuery = query.split(separator);
let len = splitQuery.length;
for (let i = 0; i < len; i++) {
let item = splitQuery[i];
let parsedItem = safeParse(itemParser.parse, item.replaceAll(encodedSeparator, separator), `[${i}]`);
if (parsedItem !== null && parsedItem !== undefined) {
parsedSet.add(parsedItem);
}
}
return parsedSet;
},
serialize: values => {
let serializedArr = [];
for (let item of values) {
let str = itemParser.serialize ? itemParser.serialize(item) : String(item);
serializedArr.push(str.replaceAll(separator, encodedSeparator));
}
return serializedArr.join(separator);
},
});
} Something like this i guess, also maybe you could include a parseAsMapOf? Just throwing ideas. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
Hey, chiming back on this discussion: we're going to add a "community parsers" section in the docs soon, would you like to add your Set parser to the list? |
Beta Was this translation helpful? Give feedback.
-
Nice implementation mate! I just wanted to share what I did also as my use-case was not as complex even though I work with HeroUI that uses react-aria under the hood. import { createParser } from 'nuqs';
import type { Selection } from '@heroui/react';
export const parseAsSelection = createParser<Selection>({
parse(queryValue) {
if (!queryValue) return new Set() as Selection;
return new Set(queryValue.split(',')) as Selection;
},
serialize(value) {
if (!(value instanceof Set)) return '';
return Array.from(value).join(',');
},
eq: (a, b) => {
const sortedA = Array.from(a).sort();
const sortedB = Array.from(b).sort();
return JSON.stringify(sortedA) === JSON.stringify(sortedB);
},
}); Example use: const [statusFilter, setStatusFilter] = useQueryState(
'status',
parseAsSelection.withDefault(new Set(['active', 'inActive'])).withOptions({ clearOnDefault: true })
); |
Beta Was this translation helpful? Give feedback.
Hey, chiming back on this discussion: we're going to add a "community parsers" section in the docs soon, would you like to add your Set parser to the list?