iway1 / react-ts-form

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

issue: Example NumberField component can't get subsequently updated by the reset function if field is empty #92

Open ingadi opened 1 year ago

ingadi commented 1 year ago

Version Number

1.4.5

Codesandbox/Expo snack

https://codesandbox.io/s/cocky-driscoll-0bpr67?file=/src/App.tsx

Steps to reproduce

  1. Go to provided code sandbox
  2. Click 'Reset to defaults' (works -> both fields get updated to their default values)
  3. Empty both fields
  4. Click 'Reset to defaults' (only the text field gets updated to it's default value )

Expected behaviour

Number fields should keep getting updated beyond the first call to reset.

Relevant log output

No response

ingadi commented 1 year ago

I got it to work by changing the example NumberField component provided in the docs to this (basically just adding a number type to the TextField component:

function NumberField() {
  const {
    field: { value, onChange },
  } = useTsController<number | string>();

  return (
    <div>
      <input
        type="number"
        value={value ?? ""}
        onChange={(e) => {
          const val = e.target.valueAsNumber;
          onChange(isNaN(val) ? "" : val);
        }}
      />
    </div>
  );
}
iway1 commented 1 year ago

thanks for the repro, seems like the issue only happens when resetting from an empty field which is interesting.

The difference with your above fix is that it's setting the form state to a string value, which is different from what the example number field does (it sets to a number instead of a string), which isn't going to validate correctly I don't think.

I think I know what's causing this though