Default Value Handling in Query Parameters with Zod #954
Unanswered
alberto-htl
asked this question in
General
Replies: 1 comment
Indeed, if there is no query value, there is nothing to parse, and so the schema is not called. One issue I see with your approach is defining default values that are time-based: the default values for For this, you may want to keep your state nullable, and apply the defaults dynamically (via nullish coalescing) after parsing, so that you always get fresh defaults. |
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
I have a scenario where I need to handle a date range in the search parameters. The date format used is MM-dd-yyyy, and I want to provide a default value server-side if the date range is not provided. Here's what I’ve implemented so far:
And the schema that I’m using:
Issue:
The code above should handle both cases: when the query is missing from the URL and when a parameter is missing from the filters.
I was expecting the .transform method in the schema to be enough to handle the default values, but it seems like when the query is missing, the validation schema is not evaluated, and the default values aren't applied as expected.
Question:
Is there a better approach to provide default values server-side without duplicating the logic in multiple places (i.e., in both the withDefault() in the searchParamsParsers and the transform() in the schema)? Any suggestions on how to ensure the schema evaluates correctly when the query is missing or incomplete?
All reactions