Search code examples
javascriptreactjsreact-reduxredux-form

Redux-form not formatting post data and [object Object] issue


I have two problems that are a result of each other. I populate two fields with initialValue data, I can then push another field to the array. The issue came about when I tried to amend the initialValue structure from:

  initialValues: {
    rockSingers: [ "Axl Rose", "Brian Johnson"]
  }

to:

  initialValues: {
    rockSingers: [{ singer: "Axl Rose" }, { singer: "Brian Johnson" }]
  }

The first problem is that the field now returns [object Object]. Upon submitting the form the correct json format is displayed until I come on to my 2nd issue... when adding a new value that does not format the same as the initialValue data - e.g.

{
  "rockSingers": [
    {
      "singer": "Axl Rose"
    },
    {
      "singer": "Brian Johnson"
    },
    "Tom Rudge"
  ]
}

Here is the codesandbox - https://codesandbox.io/s/8kzw0pw408


Solution

  • Modify renderRockSingers so that you are grabbing the object, not a string.

    const renderRockSingers = ({ fields }) => (
      <div>
        <h3>Rock Singers:</h3>
        {fields.map((rockSinger) => (
          <div>
            <Field name={`${rockSinger}.singer`} key="index" component="input" />
          </div>
        ))}
        <button type="button" onClick={() => fields.push()}>
          Add more
        </button>
      </div>
    );

    More on the FieldArray component here: fieldarrays