Unable to set initialValue on final form array

1.4k Views Asked by At

I'm having problems setting the initialValue of a FieldArray component in React Final Form. It works when I set it on the Form component, but not on the FieldArray. Please see below CodeSandbox examples:

On FieldArray: https://codesandbox.io/s/react-final-form-field-arrays-vq9pz

On Form: https://codesandbox.io/s/react-final-form-field-arrays-v90nn

I would prefer to have it set on the FieldArray, which seems like it should be possible if I look at the documentation here. Has anyone else come across this?

3

There are 3 best solutions below

0
On

Usually I will create a mutator like this:

   <Form
     mutators={{
       ...arrayMutators,

       addCustomer: (_, state, { changeValue }) => {
         changeValue(state, "customers", (v) => [
           ...v || [],
           { firstName: 'abc', lastName: 'efg' },
         ]);
       },

     }}
     ...

and change the Add Customer button onClick={() => form.mutators.addCustomer()}

2
On

You can define const customer = { firstName: "test", lastName: "test" }; and then use it in here:

<button type="button" onClick={() => push("customers", customer)}>
  Add Customer
</button>

Here is CodeSandbox example https://codesandbox.io/s/react-final-form-field-arrays-vmmf3?fontsize=14.

0
On

The implementation of initialValue was introduced in version 3.1.3.

Change the version of react-final-form-arrays to 3.1.3 in the sandbox.

You will also need to change the version of react-final-form to 6.5.2