Skip to content

Consider providing access to state context in onSubmit #6

@10xjs

Description

@10xjs

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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions