Reputation: 153
I currently have a form in Redux-form that pulls in initial values from an API. However, whenever I edit one of those values and then submit the form, it is returning the old initial value (doesn't seem to be updating). I would like to be able to edit the field, submit, then update the initial value to the new value so that when the form is loaded again, you will see the most recent edit/change. Right now, this is how I am initializing my data:
componentDidMount(){
this.props.offerCallBack()
.then(c => {
this.setState({
offerContent: c,
});
this.handleInitialize();
})
.catch(error => {
console.log(error);
});
}
handleInitialize() {
const offerContent = JSON.parse(this.state.offerContent.content);
const initData = {
"questionText": offerContent.question_text === null ? "Enter Question Text" : offerContent.question_text,
"questionType": offerContent.question_type === null ? "" : offerContent.question_type,
this.props.initialize(initData);
}
Here is my submit function:
onSubmit(values) {
console.log(values);
const questionData = Object.assign({}, values, { questionText: undefined });
this.props.saveOffer(questionData);
}
Example of one of my fields inside my
<Field
name="questionText"
type="text"
id="questionText"
component={renderField}
label="Question Text"
onChange={this.handleChange}
/>
Then the bottom of my redux form
const form = reduxForm({
form: 'offerquestion',
enableReinitialize: true
});
function mapStateToProps(state) {
return {
offerContent: state.offerContent,
initialValues: state.offerContent
};
}
export default connect(mapStateToProps)(form(OfferExample));
Any and all help will be greatly appreciated, I've been stuck on this for days!
Upvotes: 0
Views: 450
Reputation: 1879
It looks like you are using the state
in the handleInitilize
method, remember that when you setState
the state don't update right the way (it is an async function). So if you add a callback to the setState, and then you call the handleInitialize
method you are sure that the value exists.
componentDidMount(){
this.props.offerCallBack()
.then(c => {
this.setState({
offerContent: c,
}, () => {
// You can handle here and make sure the state has updated
console.log( this.state.offerContent );
this.handleInitialize();
});
})
.catch(error => {
console.log(error);
});
}
Upvotes: 1