Nuqs array toggle

How do I toggle value on nuqs array? Is this best way or is there other ways of doing it?
"use client";

import { Button } from "@/components/ui/button";
import { parseAsArrayOf, parseAsInteger, useQueryState } from "nuqs";

export const Example = () => {
const [colors, setColors] = useQueryState(
"colors",
parseAsArrayOf(parseAsInteger)
.withOptions({ shallow: false })
.withDefault([])
);

return (
<div>
<p>client: {JSON.stringify(colors)}</p>
<div>
<Button
onClick={() => {
setColors([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
}}
>
Add all colors
</Button>

<Button onClick={() => setColors([])}>Clear colors</Button>

<Button
onClick={() =>
setColors((prev) => {
return prev.includes(1)
? prev.filter((color) => color !== 1)
: [...prev, 1];
})
}
>
Toggle 1
</Button>
<Button
onClick={() =>
setColors((prev) => {
return prev.includes(2)
? prev.filter((color) => color !== 2)
: [...prev, 2];
})
}
>
Toggle 2
</Button>
</div>
</div>
);
};
"use client";

import { Button } from "@/components/ui/button";
import { parseAsArrayOf, parseAsInteger, useQueryState } from "nuqs";

export const Example = () => {
const [colors, setColors] = useQueryState(
"colors",
parseAsArrayOf(parseAsInteger)
.withOptions({ shallow: false })
.withDefault([])
);

return (
<div>
<p>client: {JSON.stringify(colors)}</p>
<div>
<Button
onClick={() => {
setColors([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
}}
>
Add all colors
</Button>

<Button onClick={() => setColors([])}>Clear colors</Button>

<Button
onClick={() =>
setColors((prev) => {
return prev.includes(1)
? prev.filter((color) => color !== 1)
: [...prev, 1];
})
}
>
Toggle 1
</Button>
<Button
onClick={() =>
setColors((prev) => {
return prev.includes(2)
? prev.filter((color) => color !== 2)
: [...prev, 2];
})
}
>
Toggle 2
</Button>
</div>
</div>
);
};
1 Reply
François Best
François Best2mo ago
Yes, pretty much the same way you would in a useState. If you want to keep the order and toggle in-place (but still return a new array), you could use the newly available .with method on arrays: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/with Look for the index first, then if it's not -1 call that (otherwise return the original to avoid a re-render).
MDN Web Docs
Array.prototype.with() - JavaScript | MDN
The with() method of Array instances is the copying version of using the bracket notation to change the value of a given index. It returns a new array with the element at the given index replaced with the given value.

Did you find this page helpful?