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>
);
};
0 Replies
No replies yetBe the first to reply to this messageJoin

Did you find this page helpful?