A common pattern is to need to update arbitrary field values while handling a submit response.
Currently this can be achieved with a ref to the Form component that shares a context with the onSubmit callback:
class CustomForm extends React.PureComponent {
formRef = React.createRef();
render() {
return (
<Form
{...this.props}
onSubmit={(values) => {
return sendFetch(values).then((response) => {
if (response.hasSomeCondition) {
formRef.current.setValue('field', value);
return Promise.reject(new SubmitValidationError(errors));
}
}};
}}
/>
)
}
}
It would be much cleaner to provide access to the state context through additional arguments of onSubmit:
const CustomForm = () => (
<Form
{...this.props}
onSubmit={(values, context) => {
return sendFetch(values, context).then((response) => {
if (response.hasSomeCondition) {
context.setValue('field', value);
return Promise.reject(new SubmitValidationError(errors));
}
}};
}}
/>
);
Questions:
- Should callback props other than
onSubmit also have access to the context?
- What part of, if not the entire context, should be provided?
- Is the first
values argument necessary if the full context is provided? The values arg and context.valueState would be the same value. Omitting the first arg and requiring the consumer to access valueState on context doesn't limit functionality, and arguably makes for a "simpler" (but less obvious) interface.
- A static reference to
context as it exists at the time onSubmit is called may be outdated by the time it is referenced. Is a getContext arg that would provide access to the latest updated context when needed a better choice?
A common pattern is to need to update arbitrary field values while handling a submit response.
Currently this can be achieved with a ref to the
Formcomponent that shares a context with theonSubmitcallback:It would be much cleaner to provide access to the state context through additional arguments of
onSubmit:Questions:
onSubmitalso have access to the context?valuesargument necessary if the full context is provided? Thevaluesarg andcontext.valueStatewould be the same value. Omitting the first arg and requiring the consumer to accessvalueStateon context doesn't limit functionality, and arguably makes for a "simpler" (but less obvious) interface.contextas it exists at the timeonSubmitis called may be outdated by the time it is referenced. Is agetContextarg that would provide access to the latest updated context when needed a better choice?