Form onValidate as a prop
See original GitHub issueHi, thank you for the great library. I have run into an issue and could use some help. If there’s an intended way for me to do this, let me know and I can close the issue.
🚀 Feature request
<Form>
should have onValidate as a prop, not part of state
Motivation
I would like to change the value of onValidate in the form. Consider if onValidate called a callback prop of the enclosing component. This callback will not get updated in the onValidate function because it was only set at the first render’s useFormState() call. There doesn’t seem to be a way to update this value when props change – again, let me know I’m missing something!
Example
The issue is illustrated here. When the parent’s onValidate prop is updated, the Form will still use the old onValidate:
const MyComponent = ({ onValidate }) => { // takes callback as a prop
const form = useFormState({ // initialize form state
values: { foo: "" },
onValidate // will not be updated when parent onValidate prop changes (!)
});
return (
<Form {...form}>
<FormInput {...form} name="foo" />
</Form>
);
};
const Example = () => {
const [count, setCount] = useState(0);
return (
<>
<Button onClick={() => setCount(count + 1)}>{count}</Button>
<MyComponent
onValidate={() => {
// Note this always prints 0, even though count is changing!
console.log(count);
}}
/>
</>
);
};
Possible implementations
Could be made similar to the onSubmit prop – which also needs to receive values.
Issue Analytics
- State:
- Created 4 years ago
- Comments:7 (4 by maintainers)
@cbush I believe the
onSubmit
prop is attached to the nativesubmit
DOM event, that’s why it works as a prop.I’ll need more time to think on this, but one thing you can do today is to use a ref to store the updated value: