Arrays example
💡
In order to handle the situation when there is only one element in the array
you have to use preprocess
explicit conversion. Alternitively, you can use
z.coerce.number().or(z.array(z.coerce.number()))
but then the returned type
is number | number[]
const { data, setState, setValue } = useUrlState(
z.object({
search: z.string(),
limit: z.coerce.number().max(100),
from: z.coerce.date().optional(),
stringArr: z.preprocess(
(v) => (Array.isArray(v) ? v : [v]), // convert to array if only one item is present
z.array(z.string()), // definition of the array items
),
numberArr: z.preprocess(
(v) => (Array.isArray(v) ? v : [v]),
z.array(z.coerce.number()), // definition of the array items
),
}),
);
return (
<ButtonsGroup>
<Button
onClick={() =>
setState({
search: 'query',
limit: 10,
from: new Date(),
stringArr: ['one', 'two'],
numberArr: [123, 321],
})
}
>
1. Set the state
</Button>
<Button
onClick={() => setValue('limit', 999)}
color="error"
disabled={!data}
>
2. Set errored state
</Button>
</ButtonsGroup>
);
State
null