Search code examples
javascriptreactjsreact-reduxredux-form

React - Redux-Form Remote Submit


I am attempting to remotely submit a form using redux-forms. My question would be, how do I execute redux actions from a function outside the component. The equivalaent of saying:

this.props.action(params);

My code is as follows:

async function submit(values) {
    return (
        //Equivalent of => this.props.addOne(values.name)
        await actions.addOne(values.name, 60)
    )
}

const renderTextField = ({ input, label, meta: { touched, error } }) =>
<TextField 
    autoFocus
    margin="dense"
    fullWidth
    type="text"
    label={label}
    {...input}
/>

class LibrarySubsectionForm extends React.Component {
render() {
    const { handleSubmit } = this.props;

    return (
        <form onSubmit={handleSubmit}>
            <Field
                component={renderTextField}
                name="name" 
                label="Subsection Name"
            />
        </form>
    )
}
}

export default compose(
connect(null, actions),
reduxForm({ form: 'AddSubsection', onSubmit: submit })
)(LibrarySubsectionForm);

Solution

  • Redux-form is passing dispatch function and props of your decorated component as second and third arguments of onSubmit handler. So basically you have access to them inside your submit function. If you are passing actions as a prop to LibrarySubsectionForm then you can access them inside submit function:

    async function submit(values, dispatch, props) {
        return await props.actions.addOne(values.name, 60);
    }