iway1 / react-ts-form

https://react-ts-form.com
MIT License
2.01k stars 35 forks source link

Schema created with 'createUniqueFieldSchema' stops working if added .optional() #50

Closed lucasjungdeveloper closed 1 year ago

lucasjungdeveloper commented 1 year ago
// components/form.ts
import { createTsForm, createUniqueFieldSchema } from '@ts-react/form'
import { z } from 'zod'

import { NumberField } from './NumberField'
import { TextField } from './TextField'

export const StringSchema = createUniqueFieldSchema(z.string(), 'string')
export const NumberSchema = createUniqueFieldSchema(z.number(), 'number')

const mapping = [
  [StringSchema, TextField],
  [NumberSchema, NumberField],
] as const

export const Form = createTsForm(mapping)
// pages/index.tsx
import { z } from 'zod'

import { Form, NumberSchema, StringSchema } from '../components/form'

const schema = z.object({
  name: StringSchema.optional(), // if .optional is added to a schema it stops working
  age: NumberSchema,
})

export function Home() {
  return (
    <Form
      schema={schema}
      onSubmit={(v) => {
        console.log(v)
      }}
      formProps={{
        className: 'flex flex-col gap-4 px-4 max-w-5xl lg:grid lg:grid-cols-2',
      }}
    />
  )
}
iway1 commented 1 year ago

Are you sure you're on the latest version 1.1.3?

This was fixed recently and is working fine on my end.

iway1 commented 1 year ago

Gonna close b/c I wasn't able to reproduce any issue with your code on the latest version. I added a test case to test for this going forward.

Reopen or leave a comment w/ reproduction if you're still having an issue after upgrading to the latest 1.1.3.

Thanks

FedeMadoery commented 1 year ago

I have the same issue, I'm working with v1.2.0... I will add a code sandbox that reproduces the error. cc: @iway1

Code sandbox that reproduces the error with minimal setup. https://codesandbox.io/embed/react-ts-form-optional-error-3oz8lk?fontsize=14&hidenavigation=1&theme=dark


Code example, just in case.

const MAX_FILE_SIZE = 1000000000000;

export const FileSchema = createUniqueFieldSchema(
  z
    .any()
    .refine((value) => !!value && !!value.file, "Upload a file is required.")
    .refine(
      (value) => value?.file?.size <= MAX_FILE_SIZE,
      `Max file size is 5MB.`
    ),
  "FileSchema"
);
const FileSchemaComponent = () => <div>{`FileSchema :)`}</div>;

// create the mapping
const mapping = [[FileSchema, FileSchemaComponent]] as const; // 👈 `as const` is necessary

// A typesafe React component
const MyForm = createTsForm(mapping);

// Creates Schema
const schema = z.object({
  file: FileSchema.optional() // if .optional is added to a schema it stops working
  // My Original file field has a description, just in case I let an example without it, the issue persists in both cases
  // fileWithDescript: FileSchema.optional().description('Label // Description') // if .optional is added to a schema it stops working
});