import * as React from 'react' import { FormComponentProps, FormContext } from './interfaces' import { connect } from 'react-redux' import { any, string } from 'prop-types' export class BaseForm extends React.Component { public static childContextTypes = { formName: string, // onSubmit: (e: any) => any, } public componentWillUnmount() { this.props.destroyForm(this.props.name) } /** * Make the form name available to child components * without explicitly passing it down to every one */ public getChildContext(): FormContext { return { formName: this.props.name, } } /** * Prevent the native onSubmit event from triggering * @param e */ public onSubmit = (e: React.SyntheticEvent) => { e.preventDefault() const { formData, name, onSubmit, submitFormValid, submitFormInvalid } = this.props const keys = Object.keys(formData) for (const field of keys) { if (formData[field] && !formData[field].valid) { // dispatch an action to say the form is submitted but invalid // and end the submission process here return submitFormInvalid(name, formData) } } // dispatch an action to say the form is submitted and valid submitFormValid(name, formData) // now call the onsubmit handler with the data if (onSubmit) { onSubmit(formData) } } }