Hacktoberfest '24: calling for reusable parsers! #676
franky47
started this conversation in
Show and tell
Replies: 1 comment
-
Let me start with one I had to build not too long ago: a function createStringSetParser(separator = ',') {
const encodedSeparator = encodeURIComponent(separator);
return createParser({
parse(query) {
const item = query.split(separator);
return new Set(item.map((tag) => tag.replaceAll(encodedSeparator, separator)));
},
serialize(value) {
return Array.from(value)
.map((item) => item.replaceAll(separator, encodedSeparator))
.join(',');
},
// Make sure to specify an equality function for data types
// that are not comparable by reference (===):
eq(a, b) {
if (a.size !== b.size) {
return false;
}
for (const item of a) {
if (!b.has(item)) {
return false;
}
}
return true;
},
});
} |
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
-
Type-safety is at the heart of why nuqs exists. It allows converting URL query strings into meaningful data types for our applications. This is done via parsers (which also deal with the serialisation part).
While nuqs provides a comprehensive set of parsers for built-in data types out of the box (boolean, numbers, dates, arrays etc), it allows you to make your own. Whether it's for a particular data type, or to customise how the value is rendered in the URL, custom parsers are a powerful way to design the URL as the first UI your users encounter even before landing on your app.
Example:
In this year's Hacktoberfest contest, I would like to invite the community to share their parsers with others, in a copy-pastable way (à la shadcn/ui, seems to be trendy these days), so we can build a library of recipes to convert our data types into pretty URLs.
I'll be setting up a section of the documentation to showcase those parsers, and PRs will be welcome to add to the list. In the mean time, you can always reply to this discussion with your parsers!
Beta Was this translation helpful? Give feedback.
All reactions