In order to use defaultValues with data fetched async we need to reset the form state. Unfortunately the reset method from react-hook-form isn’t exported for our use.
See reactjs - DefaultValues of react-hook-form is not setting the values to the Input fields in React JS - Stack Overflow for the problem that arises.
Steps to reproduce:
- have a blank form
- fill in details
- save to database
- open form again and load values in from database, setting them as defaultValues for the fields
- edit one field
- save form
Expected:
- all values posted as payload
Actual:
- only the one value changed is posted because form state hasn’t been “reset”
2 Likes
I can confirm this behaviour. I have the same problems.
I have in some cases made a onchange event on the fields to ensure they are changed. But that is a bad solution for something as simple as clearing the fields on submit, but I don’t have any other options.
Atlassian please, make the reset method available!
Hi @SeanCurtisHeapsGoodS , unfortunately the reset method isn’t exposed at the moment as it relies on refs which isn’t compatible with UI Kit right now. As a work around, I suggest fetching the default values before calling the hook and rendering the form.
import ForgeReconciler, {
Button,
Form,
Label,
Spinner,
Textfield,
useForm,
} from "@forge/react";
import React, { useEffect, useState } from "react";
type DefaultValues = {
name: string;
};
export const NameForm = ({
defaultValues,
}: {
defaultValues: DefaultValues;
}) => {
const { register, handleSubmit } = useForm({ defaultValues });
return (
<Form onSubmit={handleSubmit((values) => console.log(values))}>
<Label labelFor="name">Name</Label>
<Textfield {...register("name", { required: true })} />
<Button type="submit">submit</Button>
</Form>
);
};
const App = () => {
const [defaultValues, setDefaultValues] = useState<DefaultValues | null>(
null
);
useEffect(() => {
setTimeout(() => {
setDefaultValues({ name: "John" });
}, 2000);
}, []);
return (
<>
{defaultValues ? <NameForm defaultValues={defaultValues} /> : <Spinner />}
</>
);
};
ForgeReconciler.render(<App />);
1 Like