Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

zod defaults not dynamic #487

Closed
1 task done
ak5 opened this issue Sep 25, 2024 · 3 comments
Closed
1 task done

zod defaults not dynamic #487

ak5 opened this issue Sep 25, 2024 · 3 comments

Comments

@ak5
Copy link

ak5 commented Sep 25, 2024

  • Before posting an issue, read the FAQ and search the previous issues.

Description
dynamic defaults always the same

MRE:
Couldn't figure out how to link my specific example, but if you replace the given schema.ts with this one, you will see the id never changes

import { z } from 'zod';
import {nanoid} from 'nanoid'

export const schema = z.object({
	id: z.string().default(nanoid),
	name: z.string().min(2),
	email: z.string().email()
});
@ak5 ak5 added the bug Something isn't working label Sep 25, 2024
@ciscoheat
Copy link
Owner

Yes, because it's only generated once, when you define it. You need to make a function that returns a new schema every time, to get a new id.

@ciscoheat ciscoheat removed the bug Something isn't working label Sep 25, 2024
@ak5
Copy link
Author

ak5 commented Sep 25, 2024

yes, it's just not what I would expect,

now I need to change the defaults on each form in load and reapply some logic in onSubmit() or something, it's cumbersome :)

@ciscoheat
Copy link
Owner

It will work in strict mode, since that won't apply default values to the validated data:

const form = await superValidate(zod(schema), { strict: true })

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants