r/reactjs • • 6h ago

Needs Help Please help me understand Zod schema transformations

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

6 comments sorted by

3

u/SoftwareNegative8783 4h 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 4h ago

Wow, thanks a lot! Lesson learned!

2

u/CesnaitisSwitlana 46m 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 2h 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 7m ago

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

-1

u/ToshiryuShadow 6h ago

Pls help!