I'm using redux-form. I'm showing initial values in input fields from the state.
When I click on reset, the input field is still showing initial values.
How can I reset the input field?
This is my code :
const mapStateToProps = (state) => {
return {
initialValues: {
name:state.userInfo.data.name,
email:state.userInfo.data.email,
phone:state.userInfo.data.phone,
city:state.userInfo.data.city.name,
}
};
}
This is how I'm calling initial value in the input field.
const renderField = ({ input, label, type, meta: { touched, error } }) => (
<div>
<input className="form-control control_new" {...input} placeholder={label} type={type}/>
{touched && ((error && <span>{error}</span>))}
</div>
)
<Field type="text" {...name} name="name" component={renderField} label="Enter Your Name" />
Thanks
import {reset} from 'redux-form';
...
dispatch(reset('myForm')); // requires form name
Harsha's answer is correct, but you can also call this.props.reset()
, which already knows your form name, from inside your decorated form component.
You can see it in action on the "Clear Values" button in the Simple Example.
TLDR: set enableReinitialize: true
on your form
I had this same problem recently and came across this post, with none of the answers working. Finally found the solution so hopefully this will help someone else. the problem is those initial values not getting reset when you reset the form. here is a github issue asking about it, and here is the current documentation about it
Upon onClick of the clear button call a different function as follows.
onClick={this.onClearChanges}
Pass the initialValues to the function this way, and as everyone mentioned, Don't forget to set enableReinitialize: true.
onClearChanges = () => {
const { reset, onClearChanges, InitialValues } = this.props;
reset();
onClearChanges(InitialValues);
};
It's also possible to reset inside of your constructor if you don't have a button with a method to call.
I'm using a Drawer Navigator to navigate to different screens(not a clickable button with an onClick method) so I had to reset
constructor(props) {
super(props);
this.props.reset(); //<-- this
}
inside of the first component to handle that specific redux form and then I set
enableReinitialize: true
for that form.