iway1 / react-ts-form

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

issue: Accessing form state disables default values #88

Closed ingadi closed 1 year ago

ingadi commented 1 year ago

Version Number

v.1.4.2

Codesandbox/Expo snack

https://codesandbox.io/s/black-mountain-14xil1?file=/src/App.tsx

Steps to reproduce

  1. Default value 'hello' appears in text field.
  2. Go to line 35 - (where you pass the result of useForm() to your form), uncomment the line and refresh.
  3. Default value doesn't appear in the text field anymore.

Expected behaviour

Default values passed into the form should appear even when form state is accessed.

Relevant log output

No response

iway1 commented 1 year ago

fixed in v1.4.3, thanks for the repro

ingadi commented 1 year ago

Just upgraded, works great but now getting the warning below... 'Cannot update a component (...) while rendering a different component (...)

warning

iway1 commented 1 year ago

going to revert for now then, will look into this some more

iway1 commented 1 year ago

you can use this for now:

useForm({
  defaultValues: {}
})

I'm not sure there's a way to make it work with the prop if that didn't work, but I'll try.

If not, I'll update the documentation in "Accessing Form State" to mention this, maybe add a warning if defaultValues and prop are both passed

ingadi commented 1 year ago

Before the fix my hacky work around was skipping the default values prop altogether and using the reset function inside a useEffect to set the form defaults on mount. Didn't get any infinite loops so ¯_(ツ)_/¯

  const form = useForm<z.infer<typeof FormSchema>>();
  const { reset } = form;

  useEffect(() => reset({ text: "hello" }), [reset]);

  return (
    <div className="App">
      <Form
        form={form}
        schema={FormSchema}
        onSubmit={(data) => {
          console.log("Got the data");
          console.log(data);
        }}
        renderAfter={() => <button>Submit</button>}
        // defaultValues={{
        //   text: "hello"
        // }}
      />
    </div>
  );
iway1 commented 1 year ago

That's what I should've done first =D.

Just released v1.4.5 with this included