Giter Club home page Giter Club logo

Comments (4)

tresorama avatar tresorama commented on September 26, 2024

Even if would be great to have a solution for this, like a standard API for transform/cast between react-hookk-form state and html widget state...


In this sandbox I tried to overcome this with a restructure of data flow.
The idea is to split the schema into 2 parts: formSchema and dataSchema.

const dataSchema = z.object({ ... }) // schema that rapresent how datasource fetched from DB looks

const formSchema = z
  .object({ ... }) // validate react-hook-form state
  .transform((input)=> // then cast types for dataSchema validation)
  .pipe(dataSchema); // Validate against the dataSchema

dataSchema is the schema used for validating at the Datasource (DB) level.

So the validation schema has three step

  1. Validate react-hook-form formValues
  2. If pass, cast types to expected type of the Datasource layer
  3. Validate against the dataSchema

This is more verbose, but more declarative and easily readable

from react-hook-form.

tresorama avatar tresorama commented on September 26, 2024

To give better context to this issue...

Goal

Let's say the you want a form with an input the let you select a date, but you want to set a default date.
Doing that when the user open the form a date is already in place (for example the "today" date)

This does not work

const Component = () => {
  const { register } = useForm({
    defaultValue: {
      day: new Date("2024-12-31"),
    }
  })

  return <input type="date" {...register('day', {valueAsDate: true })} />
}

Output:
Schermata 2024-04-22 alle 18 43 27

This works - use Controller API

If you instead switch from register API to <Controller> API you can:

  • edit how reach-hook-form => set value to => html input element
  • edit how react-hook-form => get value from the onChange event and set it to => react-hook-form state
const Component = () => {
  const { register } = useForm({
    defaultValue: {
      day: new Date("2024-12-31"),
    }
  })

  return (
  <Controller
    control={control}
    name="day"
    render={({field}) => (
      <input
        {...field}
        type="date"
        value={field.value ? field.value.toISOString().substring(0,10) : undefined}
        onChange={( {target:{value}} ) => field.onChange( value === '' ? undefined : new Date(value) ) }
      />
    )}
  />
  )
}

Consideration

But this means that you cannot choose which api to use (register or Controller), but as soon as you need a date input you MUST use the controller api, which is less performant

Open Question

Why not exposed in the registr api a similar way to manipulate the value between react-hook-form state and html input state (DOM state) ??
Something like

<input 
  type="date" 
  {...register("day", {
    // input value => react-hook-form state
    getValueFromInputAs:  value => value === '' ? undefined : new Date(value), 
    // react-hook-form-state => input value
    setValueToInputAs: value => value ? value.toISOString().substring(0,10) : undefined, 
  })}
/>

This works - use string instead of Date and accept a complex validation schema

Because this doesn't work ...

const schema = z.object({
  day: z.date(),
});
const Component = () => {
  const { register } = useForm<z.input<typeof schema>>({
    defaultValue: {
      day: new Date("2024-12-31"),
    }
  })
  // ...
}

... you can switch the field type from Date to string like ...

const { register } = useForm<z.input<typeof schema>>({
    defaultValue: {
      day: "2024-12-31", // now it's a string
    }
  })

... but the validation schema will complain (showing Typescript errors). You can fix this by adding more complexity to the schema, with downside of coupling the schema with HTML input behavior.

const schema = z.object({
  // 1. validate html input values
  day: z.string().min(1, "Required field"),
}).transform(input => ({
 // 2. If step 1 is valid, cast/coerce data types for the step 3
  day: new Date(input.day),
}).pipe(z.object({
  // 3. validate data
  day: z.date(),
});

... and updating also useForm generic types to have correct inference inside handleSubmit

type SchemaInput = z.input<typeof schema>;
type SchemaOutput = z.output<typeof schema>;

const { register, handleSubmit } = useForm<SchemaInput, any, SchemaOutput>({
    defaultValue: {
      day: "2024-12-31", // now it's a string
    }
  })

<form onSubmit={handleSubmit((formValues) => {
  // here formValues has SchemaOutput types and not SchemaInput
  // so "formValues.day" is of type Date, not string 
}}

from react-hook-form.

tresorama avatar tresorama commented on September 26, 2024

Feature request

Why not exposeing in the register api a way to manipulate the value between react-hook-form state and DOM html input state ??
This will give "parity" with the Controller API.

Something like

<input 
  type="date" 
  {...register("day", {
    // input value => react-hook-form state
    getValueFromInputAs:  value => value === '' ? undefined : new Date(value), 
    // react-hook-form-state => input value
    setValueToInputAs: value => value ? value.toISOString().substring(0,10) : undefined, 
  })}
/>

from react-hook-form.

kujohn avatar kujohn commented on September 26, 2024

I am having this issue as well. defaultValue doesn't work at all with type=date inputs.

from react-hook-form.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.