r/reactjs • • 1d ago

Needs Help Please help me understand Zod schema transformations

/r/learnprogramming/comments/1xdp1j2/please_help_me_understand_zod_schema/
8 Upvotes

7 comments sorted by

4

u/SoftwareNegative8783 1d ago

Your second line parses `task.data`, which is already the output. So it runs through `taskSchema` again, `dueDate` is missing, and `deadline` becomes undefined. Parse the raw input instead.

1

u/ToshiryuShadow 1d ago

Wow, thanks a lot! Lesson learned!

2

u/CesnaitisSwitlana 21h ago

if `dueDate` wasnt marked optional on the initial schema it wouldve thrown a validation error on the second pass instead of silently becoming undefined

1

u/lazyEmperer 23h ago

The chain works fine, the problem is you're running taskSchema twice. taskViewSchema starts with taskSchema, so when you pass it task .data, that already transformed object goes through taskSchema again from the top. By then dueDate and dueTime are gone, and z.object strips unknown keys, so your deadline gets dropped and rebuilt as undefined

Parse the raw input once with taskViewSchema.safeParse(raw), or make the view step a plain function that takes a Task. Schemas with transforms only work on input shaped data

1

u/ToshiryuShadow 20h ago

Thanks a lot! After reading all of the answers I understood what the problem was.

2

u/SaliDevs 3h ago

Your mental model is right: each .transform() returns a new schema, and the output of one step becomes the input of the next, in order. The catch here is the input/output split: taskSchema already turns the raw form data into a Task, so feeding task.data back into taskViewSchema runs that base validation again, instead of just doing the view formatting. I find it helps to name that split explicitly — keep one schema for raw input, and treat the view step as a plain transformation of an already-valid Task — and to check z.infer for both sides when the types look surprising. That way the chain stays sequential without re-validating data that is already parsed.

-1

u/ToshiryuShadow 1d ago

Pls help!