iway1 / react-ts-form

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

issue: parse schema with createUniqueFieldSchema in Nextjs api route not working #130

Open voskuh opened 11 months ago

voskuh commented 11 months ago

Version Number

1.8.0

Codesandbox/Expo snack

No response

Steps to reproduce

Hi,

I'm submitting the values of a form to a nextjs api route. Then in the api route, I'm trying to parse the values to check whether the post body is in the expected format. It's working as expected when using a schema without a createUniqueFieldSchema. But when using a field with createUniqueFieldSchema I get an error about using createContext in a server component. And that's only allowed in client components.

//my custom field schema
export const TextareaSchema150 = createUniqueFieldSchema(
  z.string()
    .min(5, { message: "Minimaal 5 karakters." })
    .max(150, { message: "Maximaal 150 karakters." }),
  "textarea"
);

// my mapping
const mapping = [
  [z.string(), TextField] as const,
  [TextareaSchema150, TextareaField] as const,

] as const;

// my form schema with the custom field schema
export const formSchemaSiteDataBasicForm = z.object({
    siteName: z.string()
        .min(2, { message: "Minimaal 2 karakters." })
        .max(50, { message: "Maximaal 50 karakters." }),
    siteSlogan: TextareaSchema150,
})

// in the nextjs api route
export async function POST(req: Request, { params }: { params: { siteId: string } }) {
    try {
      const siteData = formSchemaSiteDataBasicForm.parse(await req.json())

Expected behaviour

zod.parse can successfully parse the posted values.
When I delete the siteSlogan field from the schema, it will parse successfully. Also tried to use the form schema from above, but parsing the values in the api route with a different schema. This also parse successfully as expected.

export const formSchemaSiteDataBasicForm = z.object({
    siteName: z.string()
        .min(2, { message: "Minimaal 2 karakters." })
        .max(50, { message: "Maximaal 50 karakters." }),
    siteSlogan: z.string()
        .min(5, { message: "Minimaal 5 karakters." })
        .max(150, { message: "Maximaal 150 karakters." }),

Relevant log output

error node_modules/react-hook-form/dist/index.cjs.js (1:1296) @ createContext
- error createContext only works in Client Components. Add the "use client" directive at the top of the file to use it.