Reputation: 9184
Now I have such error:
Unhandled Rejection (SubmissionError): Submit Validation Failed
27 | .catch(err => {
> 28 | return ErrorHandler.raiseAnError(err);
29 | });
Here is my code:
TractorForm.js
import React, { Component } from "react";
import PropTypes from "prop-types";
import { reduxForm } from "redux-form";
import FormInput from "../Shared/FormInput";
import GlobalConst from "../GlobalConst";
import { Link } from "react-router-dom";
import SelectInput from "../Shared/SelectInput";
import ErrorHandler from "../ErrorHandler";
const manufacturers = ["DAF", "VOLVO", "SCANIA", "MAN", "IVECO"];
class TractorFormWrapper extends Component {
state = {
loading: false,
isSubmitted: false
};
onFormSubmit = e => {
e.preventDefault();
this.setState({ isSubmitted: true });
if (this.props.valid) {
this.setState({ loading: true });
this.props
.handleSubmit(e)
.then(() => alert("is ok!"))
.catch(err => {
return ErrorHandler.raiseAnError(err);
});
}
};
render() {
const { submitText, error } = this.props;
const { loading, isSubmitted } = this.state;
const formClassNames = loading ? "ui form loading" : "ui form";
return (
<form className={formClassNames} onSubmit={this.onFormSubmit}>
<div className="ui grid fields">
<div className="sixteen wide eight wide computer column">
<SelectInput
name="manufacturer"
type="text"
label="Производитель"
validations={[GlobalConst.REQUIRED]}
isSubmitted={isSubmitted}
values={manufacturers}
/>
</div>
<div className="sixteen wide eight wide computer column">
<FormInput
name="model"
type="text"
label="Модель"
validations={[GlobalConst.REQUIRED]}
isSubmitted={isSubmitted}
/>
</div>
<div className="sixteen wide column">
<FormInput
name="description"
type="textarea"
label="Описание"
isSubmitted={isSubmitted}
/>
</div>
</div>
{error && (
<div className="ui red message">
<strong>{error}</strong>
</div>
)}
<div className="ui fluid buttons">
<button
className="ui primary button"
type="submit"
disabled={loading}
>
{submitText}
</button>
<Link to="/tractors" className="ui button">
Отмена
</Link>
</div>
</form>
);
}
}
let TractorForm = {};
TractorForm.propTypes = {
submitText: PropTypes.string
};
TractorForm.defaultProps = {
submitText: "Отправить"
};
TractorForm = reduxForm({
form: "tractor"
})(TractorFormWrapper);
export default TractorForm;
TractorAdd.js
import React, { Component } from "react";
import TractorForm from "./TractorForm";
import TractorApi from "./TractorApi";
import { toast } from "react-semantic-toasts";
import ErrorHandler from "../ErrorHandler";
class TractorAdd extends Component {
state = {};
submit = values =>
TractorApi.create(values).then(
() => {
toast({
type: "success",
icon: "truck",
title: "Тягач создан",
description: ""
});
this.props.history.push("/tractors");
},
error => {
return Promise.reject(error);
}
);
render() {
return (
<div>
<TractorForm onSubmit={this.submit} submitText="Создать" />
</div>
);
}
}
export default TractorAdd;
ErrorHandler.js
import { SubmissionError } from "redux-form";
export default {
raiseAnError: error => {
if (
error.response.data.hasOwnProperty("message") &&
error.response.data.hasOwnProperty("stackHighlighted")
) {
throw new SubmissionError({
_error: error.response.data.hasOwnProperty("message") || "error"
});
} else {
const errKeys = Object.keys(error.response.data);
const errObj = {};
for (const errItem of errKeys) {
errObj[errItem] = error.response.data[errItem]["message"];
}
errObj["_error"] = "Произошла ошибка!";
throw new SubmissionError(errObj);
}
}
};
why do I need this in form instead of add component? so I can fix logic with loading
state variable and re-submit form
also my _error
isn't working for some reasons, but I've done everything as in doc: https://redux-form.com/7.3.0/examples/submitvalidation/
what I do wrong and how to handle SubmissionError in form component?
Upvotes: 2
Views: 5927
Reputation: 18644
The reason your error handling is not working is because you should throw new SubmissionError
in the handleSubmit
function itself, like the example you linked:
<form onSubmit={handleSubmit(submit)}>
function submit(values) {
return sleep(1000).then(() => {
// If error
throw new SubmissionError({
password: 'Wrong password',
_error: 'Login failed!'
})
// The rest logic here ...
})
}
So you should refactor your code a little bit, something like that (follow the comments):
<form className={formClassNames} onSubmit={handleSubmit(values => {
// 1. Your submit logic should be here.
// 2. Better to organize it in a stand-alone function, as `submit` function from the above example.
// 3. If you throw SubmissionError here, the error handling will work.
throw new SubmissionError({
_error: 'Error'
})
)}>
Try to tune-up and simplify your code, like the official library example you provided.
Update 1 - almost a complete example. Please follows the comments strictly:
* I removed some unrelated to the problem code blocks
TractorForm - it will be reused for both Edit and Add (Create) actions.
class TractorForm extends Component {
render() {
const { handleSubmit, error } = this.props;
return (
<form onSubmit={handleSubmit}>
// Rest input fields should be here ...
{ error && (
<div className="ui red message">
<strong>{error}</strong>
</div>
)}
<div className="ui fluid buttons">
<button
className="ui primary button"
type="submit"
disabled={loading}
>
{submitText}
</button>
</div>
</form>
);
}
}
export default reduxForm({
form: "tractor"
})(TractorForm);
TractorAdd - For adding a new Tractor. The same logic, you can apply for Edit Tractor. You have to create a new TractorEdit
component, that will pass down onSubmit
function to TractorForm
.
class TractorAdd extends Component {
onSubmit (values) {
// Please make sure here you return the promise result. It's a `redux-form` gotcha.
// If you don't return it, error handling won't work.
return TractorApi.create(values).then(
() => {
toast({
type: "success",
icon: "truck",
title: "Тягач создан",
description: ""
});
this.props.history.push("/tractors");
},
error => {
// 1. Here you should throw new SubmissionError.
// 2. You should normalize the error, using some parts of `ErrorHandler` function
throw new SubmissionError(error)
}
);
}
render() {
return <div>
<TractorForm onSubmit={this.onSubmit} submitText="Создать" />
</div>
}
}
export default TractorAdd;
Update 2 - keep you implementation as it is, but change a little bit your TractorFormWrapper
onFormSubmit
and its usage:
Documentation explanations here.
TractorForm
class TractorFormWrapper extends Component {
state = {
loading: false,
isSubmitted: false
};
onFormSubmit = data => {
this.setState({ isSubmitted: true });
if (this.props.valid) {
this.setState({ loading: true });
// `onSubmit` comes from `TractorAdd`
return this.props.onSubmit(data)
.then(() => alert("is ok!"))
.catch(err => {
return ErrorHandler.raiseAnError(err);
});
}
};
render() {
const { handleSubmit } = this.props
return <form onSubmit={handleSubmit(this.onFormSubmit)}>The rest logic is here ...</form>
}
}
let TractorForm = {};
TractorForm.propTypes = {
submitText: PropTypes.string
};
TractorForm.defaultProps = {
submitText: "Отправить"
};
TractorForm = reduxForm({
form: "tractor"
})(TractorFormWrapper);
export default TractorForm;
Upvotes: 2