I am using Redux Form.
I want to reset Form if the data is sent successfully.
import React, { Component } from "react";
import {
BrowserRouter as Router,
Route,
Switch,
withRouter
} from 'react-router-dom';
import CommentForm from '../components/CommentForm';
import { connect } from "react-redux";
import {authHeader} from '../components/auth-header';
import $ from 'jquery';
import { reset, reduxForm } from 'redux-form';
const createBlogComment = (data) => {
return fetch(CelestialSettings.URL.api + '/comments', {
method: 'post',
headers: {
...authHeader(),
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
}).then(res => {
if (res.status === 401) {
$('.thecmstatus').removeClass('success').addClass('error').html('There is something wrong while posting a comment');
return false;
}
if (res.status === 400) {
$('.thecmstatus').removeClass('success').addClass('error').html('There is something wrong while posting a comment');
return false;
}
if (res.status === 201) {
$('.thecmstatus').removeClass('error').addClass('success').html('Your comment will be visible after approval');
setTimeout(function() {
$('.thecmstatus').html('');
}, 3000);
return true;
}
}).catch(err => err);
}
class CommentFormToAPI extends Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(content) {
let APIdata = {...this.props.addComment, content:content.commentcontent};
createBlogComment(APIdata);
if(createBlogComment(APIdata)){
//I use this but it is wrong.
dispatch(reset('CommentForm'));
}
}
render() {
return (
<div>
<CommentForm onSubmit={this.handleSubmit}></CommentForm>
</div>
);
}
}
function mapStateToProps(state){
return {
addComment: state.addComment,
};
};
export default connect(mapStateToProps)(withRouter(CommentFormToAPI));
I can handle the submission since API sent but I do not know how to reset Redux form. Can you please suggest me.
I took a look here and I use the last way (D). https://redux-form.com/6.0.0-alpha.4/docs/faq/howtoclear.md/
Thank you so much.
Pass dispatch
to your createBlogComment function:
createBlogComment(APIdata, dispatch)
Then, in case of 201
response:
if (res.status === 201) {
$('.thecmstatus').removeClass('error').addClass('success').html('Your comment will be visible after approval');
setTimeout(function() {
$('.thecmstatus').html('');
}, 3000);
dispatch(reset('YourFormName'));
return true;
}
Make sure to import reset
function from redux-form
.