Skip to content

Instantly share code, notes, and snippets.

@gaku-sei
Created April 16, 2021 08:43
Show Gist options
  • Save gaku-sei/9f6e7267475ed160cbba2fe540b6677a to your computer and use it in GitHub Desktop.
Save gaku-sei/9f6e7267475ed160cbba2fe540b6677a to your computer and use it in GitHub Desktop.
module Form = {
@react.component
let make = () => {
let {clearErrors, control, formState: {errors}, handleSubmit} = Hooks.Form.use(
~option=Hooks.Form.option(
~mode=#onBlur,
~shouldFocusError=false,
~defaultValues=Js.Dict.fromArray([(Values.title, Value.make(""))]),
(),
),
(),
)
let onSubmit = (data, _event) =>
switch data->ReCode.Decode.decodeJson(Values.decoder) {
| Ok(value) => Js.log2("ok", value)
| Error(error) => Js.log2("ko", error)
}
<form onSubmit={handleSubmit(. onSubmit)}>
<Controller
name=Values.title
control
rules={Rules.make(~required=true, ())}
render={({field: {name, onBlur, onChange, ref, value}}) =>
<div>
<label> {name->React.string} </label>
<input name onBlur onChange onFocus={_event => clearErrors(. Values.title)} ref value />
<ErrorMessage errors name message={"Required"->React.string} />
</div>}
/>
<input type_="submit" />
</form>
}
}
open ReCode.Decode
open ReCode.DecodeExtra
type t = {title: string}
let title = "title"
let make = title => {title: title}
let decoder = pure(make)->Object.required(title, string->String.min(1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment