Sankar
Sankar

Reputation: 6522

throwing redux-form submissions errors from handleSubmit functions

I have a redux-form which has a handleSubmit function which I use to make some async http server authentication. If the authentication fails for some reason, I want to throw a redux-form error. If I throw a "SubmissionError" I get an error message saying: Uncaught (in promise)

My code:

class MyLoginForm extends Component {
    handleSubmit({ email, password }) {
        axios.post("http://API_SERVER/login", null, { withCredentials: true, auth: { username: email, password: password } })
            .then((response) => {
                console.log('HTTP call success. JWT Token is:', response.data);
            })
            .catch(err => {
                console.log(err)
	>>>>	WHAT TO DO TO CONVEY THE ERROR IN THE REDUX-FORM <<<<
                if (err.response) {
                    
                    if (err.response.status !== 200) {
                        console.log("Unexpected error code from the API server", err.response.status);
                        throw new SubmissionError({ _error: 'HTTP Error. Possibly invalid username / password' });
                    }
                    return
                }
                throw new SubmissionError({ _error: 'HTTP Error. Please contact Helpdesk' });
            });
    }

    render() {
        const { error, handleSubmit, pristine, reset, submitting } = this.props
        return (
            <form onSubmit={handleSubmit(this.handleSubmit.bind(this))}>
                <Field name="email" type="email" component={renderField} label="Email Address" />
                <Field name="password" type="password" component={renderField} label="Password" />
                {error && <strong>{error}</strong>}
                <div>
                    <button type="submit" disabled={submitting}>Log In</button>
                    <button type="button" disabled={pristine || submitting} onClick={reset}>Clear Values</button>
                </div>
            </form>
        )
    }
}

export default connect(null, actions)(reduxForm({
    form: ‘MyLoginForm' // a unique identifier for this form
})(MyLoginForm));

I want a solution to update/render the error message in the redux-form itself without creating anything in the global state, reducers, etc.

Upvotes: 3

Views: 1426

Answers (1)

Sankar
Sankar

Reputation: 6522

The solution is simple. I just had to add a return in front of the axios call. So the updated code will be like:

handleSubmit({ email, password }) {
    return axios.post("http://API_SERVER/login", null, { withCredentials: true, auth: { username: email, password: password } })
        .then((response) => {
            console.log('HTTP call success. JWT Token is:', response.data);
        })

Upvotes: 6

Related Questions