Redux-form: How To Load Values(edit Mode) From A Api Call To Form When In Modal Pop Up?
Solution 1:
Here is the flow:
componentDidMount() {
this.props.loadClient(); // dispatch an action from your component
}
action dispatcher
loadClient() {
// API call here
}
Store the result in redux reducer
case LOAD_PROFILE_SUCCESS:
return {
...state,
data: action.result // save your data here
};
Then add the initialValues props to the @connect decorator
@connect(state => ({
initialValues: state.profile.data // load the saved data here
}),
{ loadClient }
)
Example: You could load the intialvalues at reduxForm itself.
letAddUser = props => {
const { handleSubmit, initialValues } = props;
return (
<formonSubmit={handleSubmit}><div><labelhtmlFor="name">Name</label><Fieldname="name"component="input"type="text" /></div><div><labelhtmlFor="email">Email</label><Fieldname="email"component="input"type="email" /></div><div><labelhtmlFor="phoneno">PhoneNo</label><Fieldname="phoneNo"component="input"type="text" /></div><buttontype="submit">Submit</button></form>
);
}
exportdefaultAddUser = reduxForm({ form: 'addUser', initialValues: {
name: "abc",
email: "abc@gmail.com",
phoneNo: "1234567890"
} })(AddUser)
Your component must have the Form component. Rest will be taken care by redux-form.
Note: Structure of your initialValues must same of form data. Field name and the object property name should be same.
for more detail, you could refer redux-form official page Here
Solution 2:
If youre using redux, you just have to map your state
in initialValues
;
Here's how I do it:
const mapStateToProps = (state) => {
const { state } = state;
return {
initialValues: state,
}
}
then set enableReinitialize
to true
FormName=reduxForm({form:'formname',enableReinitialize :true})(FormName);
then connect
your app to your redux store
export default connect(mapStateToProps)(FormName);
Solution 3:
Thank you @Sachidhanandhan!
Here's what I did -
- Defined the
reduxForm
withenableReinitialize: true
- In the
mapStateToProps
ofconnect()
, I initialized the data that I received via API and stored in State withinitialValues
- Connected the
reduxForm
withconnect()
=> This was the order I missed earlier
It is working like a charm now.
Cheers!
Solution 4:
enableReinitialize : boolean [optional] When set to true, the form will reinitialize every time the initialValues prop changes. Defaults to false. If the keepDirtyOnReinitialize option is also set, the form will retain the value of dirty fields when reinitializing.
Set this to true
Post a Comment for "Redux-form: How To Load Values(edit Mode) From A Api Call To Form When In Modal Pop Up?"