0

I am creating a settings form using redux in react. I want to create the form dynamically so any number of settings can be added on the backend and show up in the form.

I have the fields generated using a map like:

const inputs = arr.map((setting, key) => {
  return  <Field
   type="textarea"
   name={setting.setting_id}
   id={setting.setting_id}
   component={renderField}
   placeholder={setting.value}
  />

In other parts of my application I used 'this.props.initialize({ nameOfField: value});' to set the initial values of the redux form. However since these are not known before hand I tried

 settings.map((setting, key) => {
   this.props.initialize({
      [setting.setting_id]: setting.value
   });
 });

This does not work as it overwrites the previous values every time it is called leaving only the last setting in the array with the proper value set.

Is there a way to collect all of my settings at once and call them in the props.initialize function or a better way to initialize all of the fields?

Edit: with reducer code

let SettingsForms =  connect(state => ({
    settings: state.settings.settings || [],
    getSettingsLoading: state.settings.getSettingsLoading || false,
}),
dispatch => ({
    getSettings: () => dispatch(getSettings()),
    updateSettings: (data) => dispatch(updateSettings(data))
}))(Settings);

export default reduxForm({
    form: "settingsForm",
})(SettingsForms);
DRuss
  • 5
  • 4
  • Can you include the code for your reducer, showing how the settings are merged into your application's state? – Dacre Denny Aug 08 '19 at 23:54
  • Updated with code thanks – DRuss Aug 09 '19 at 00:10
  • Thanks - that looks like the code connecting your SettingsForms to the store. The reducer will typically container a switch/case block. Can you include that please? Can you also include the code for `updateSettings()`? – Dacre Denny Aug 09 '19 at 00:26

1 Answers1

0

Just came across this answer here:

Set value in field in redux form

I changed my initialize props to dispatch(change())

settings.map((setting, key) => {
    this.props.dispatch(change('settingsForm', setting.setting_id, setting.value));
});

this is called in the component did mount method and works perfectly.

DRuss
  • 5
  • 4