final-form / react-final-form-arrays

A component for rendering and editing arrays 🏁 React Final Form
MIT License
205 stars 70 forks source link

Problem with initialValues, FieldArray and unshift #137

Open magnusheino opened 4 years ago

magnusheino commented 4 years ago

Hi.

I have a form with some initial values. I use FieldArray to render. If i use push to add empty entries, everything works just fine. But if I use unshift (and I want to insert at top), form is completely broken.

I have managed to trim down my problem to this sandbox:

https://codesandbox.io/s/react-typescript-343gf

In that sandbox, you can toggle any checkbox and remove/add new entries.

Go ahead and change row 70 from

push("sla", undefined);

to

unshift("sla", undefined);

Once you click on "Create new" now, the form is broken. The new item is checked (should be unchecked), and you cannot toggle any checkboxes...

Is this a bug, or am I not seeing the obvious error in my code?

magnusheino commented 4 years ago

Inspired by https://github.com/final-form/react-final-form-arrays/issues/121 I replaced the push/unshift call with a custom mutator, newSla that inserts a new entry before the old entries, Works just fine... seems to me that this should be identical to the built in unshift, but apparently not.

<Form
                onSubmit={onSubmit}
                mutators={{
                    ...arrayMutators,
                    newSla: (args, state, tools) => {
                        const sla = tools.getIn(state, 'formState.values.sla') || []
                        const newState = tools.setIn(state, 'formState.values.sla', [createEmptySla(), ...sla])
                        Object.assign(state, newState)
                    },
                }}