Reputation: 397
I'm building an edit button for my CRUD app. In this component, each individual 'rating' is mapped into one of these components. The component starts out be displaying the rating as stored in the DB, but users can press the edit button, and it turns into a form! (eventually, I'll get initial values to populate the form fields with the data displayed in the alternate render option).
Right now for the edit button, I have a custom submit handler receiving the submitted data from the two form fields as 'formProps'. However, before passing these off to the backend API, I ALSO need to figure out how to tie an id or something to the submit handler.
As seen in the component right below the form, this whole child component has access to the necessary passed down from the parent which can accessed as 'this.props.id'. Is there anyway to bundle 'this.props.id' with formProps before the handleSubmit takes it all to Redux Actions?
class Rating extends Component{
constructor(props){
super(props);
this.state = {
formClass: "notShowing",
ratingClass: "showing"
}
}
renderForm = () => {
this.state.formClass === "notShowing"
? this.setState({formClass: "showing", ratingClass: "notShowing"})
: this.setState({formClass: "notShowing", ratingClass: "showing"})
}
onSubmit = (formProps) => {
console.log("this is what the submitHandler recieves;", formProps);
this.props.editRating(formProps, () => {
this.props.history.push('/userDashboard');
});
}
render() {
const { handleSubmit, reset } = this.props;
return (
<div className="card darken-1" key={this.props._id}>
<div className={this.state.formClass}>
<form onSubmit={handleSubmit(this.onSubmit)}>
<p>What are you rating?</p>
<fieldset>
<Field
name="title"
type="text"
component="input"
autoComplete="none"
/>
<p>Add your rates!</p>
<Field
name="value"
type="number"
component="input"
autoComplete="none"
/>
</fieldset>
<button onClick={this.renderForm} type="submit" className="teal btn-flat right white-text">Submit</button>
</form>
<button onClick={this.renderForm}>Cancel</button>
</div>
<div className={this.state.ratingClass}>
<div className="card-content">
<span className="card-title">{this.props.title}</span>
<p>{this.props.value}</p>
<button onClick={this.renderForm}>Edit</button>
<button onClick={() => this.props.deleteRating(this.props.id)}>Delete</button>
</div >
</div>
</div>
);
}
}
function mapStateToProps({ratings}) {
return { ratings };
}
export default compose(
connect(mapStateToProps, actions),
reduxForm({ form: 'editRating' })
)(Rating);
Upvotes: 0
Views: 1598
Reputation: 8023
You can use the third parameter of the handleSubmit
function.
onSubmit = (values, _, props) => {
console.log(values, props.id);
...
}
...
const { handleSubmit, reset } = this.props;
<form onSubmit={handleSubmit(this.onSubmit)} .../>
Reference: https://redux-form.com/7.4.2/docs/api/reduxform.md/#-code-onsubmit-function-code-optional-
Upvotes: 3