react-hook-form: Unexpected fields values with useFieldArray when setting defaultValues

Describe the bug I’m not 100% sure that this is a bug, but I know that what is happening is not what I expected.

When setting defaultValues on an array with useForm, I would expect the result fields array using useFieldArray to contain those values as-is rather than becoming mangled.

Example:

// In our case, the default values match a GraphQL schema so
// we can't necessarily change the shape

const { control } = useForm({
  defaultValues: {
    sources: ['abc.com', 'def.com']
  }
});
const { fields } = useFieldArray({ control, name: 'sources' });

console.log('fields', fields); 

// Expected output
/**
[{
  "value": "abc.com",
  "id": "5f0137bf-e201-425e-a7b0-f6cf76e0b3ca"
},
{
  "value": "def.com",
  "id": "5a93295c-7d9e-4762-a003-52406a611882"
}]
*/

// Actual output:
/**
[{
  "0": "a",
  "1": "b",
  "2": "c",
  "3": ".",
  "4": "c",
  "5": "o",
  "6": "m",
  "id": "5f0137bf-e201-425e-a7b0-f6cf76e0b3ca"
},
{
  "0": "d",
  "1": "e",
  "2": "f",
  "3": ".",
  "4": "c",
  "5": "o",
  "6": "m",
  "id": "5a93295c-7d9e-4762-a003-52406a611882"
}]
*/ 

This issue then snowballs into other issues when trying to display, append, delete, etc the values of the fields, but I figured I’d start here and step through the other issues only if needed.

To Reproduce Steps to reproduce the behavior:

  1. Go to https://codesandbox.io/s/upbeat-bose-pt26m
  2. Look at console
  3. See issue described above

Codesandbox link https://codesandbox.io/s/upbeat-bose-pt26m

Expected behavior See Expected output in the code snippet above.

Desktop (please complete the following information):

  • OS: Windows 10
  • Browser: Chrome
  • Version: 79.0.3945.130

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Reactions: 2
  • Comments: 18 (16 by maintainers)

Commits related to this issue

Most upvoted comments

yes we only support objects

Are you open to supporting strings and arrays as well as objects? It seems like a useful feature to me (obviously 😄). We can probably work out an API that is not a breaking change.

The change I proposed above would be a breaking change, but seems cleaner to me. A non-breaking solution would be to set a value property only when the incoming value is not an object. I’m happy to open a PR for either solution, just let me know.

thanks, i added some feedback take a look there 😃

Ah ok, I only included watch to compare the values side by side. The values inside of fields are what I was trying to point out. I removed watch from the codesandbox example. It’s possible I’m misunderstanding something, in which case I wouldn’t mind seeing that updated documentation. 😄