Skip to content

Commit 7ee1ef8

Browse files
perrin4869erikras
authored andcommitted
When removing fields, rename new ones (final-form#39)
1 parent 27acc9a commit 7ee1ef8

File tree

2 files changed

+66
-2
lines changed

2 files changed

+66
-2
lines changed

src/remove.js

+7-2
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import moveFieldState from './moveFieldState'
55
const remove: Mutator<any> = (
66
[name, index]: any[],
77
state: MutableState<any>,
8-
{ changeValue }: Tools<any>
8+
{ changeValue, renameField }: Tools<any>
99
) => {
1010
let returnValue
1111
changeValue(state, name, (array: ?(any[])): any[] => {
@@ -30,7 +30,12 @@ const remove: Mutator<any> = (
3030
// shift all higher ones down
3131
delete state.fields[key]
3232
const decrementedKey = `${name}[${fieldIndex - 1}]${tokens[2]}`
33-
moveFieldState(state, backup.fields[key], decrementedKey, backup)
33+
if (backup.fields[decrementedKey]) {
34+
moveFieldState(state, backup.fields[key], decrementedKey, backup)
35+
} else {
36+
// take care of setting the correct change, blur, focus, validators on new field
37+
renameField(state, key, decrementedKey)
38+
}
3439
}
3540
}
3641
})

src/remove.test.js

+59
Original file line numberDiff line numberDiff line change
@@ -160,4 +160,63 @@ describe('remove', () => {
160160
}
161161
})
162162
})
163+
164+
it('should remove value from the specified index, and handle new fields', () => {
165+
const array = ['a', { key: 'val' }]
166+
const changeValue = jest.fn()
167+
const renameField = jest.fn()
168+
function blur0() {}
169+
function change0() {}
170+
function focus0() {}
171+
function blur1() {}
172+
function change1() {}
173+
function focus1() {}
174+
function blur2() {}
175+
function change2() {}
176+
function focus2() {}
177+
const state = {
178+
formState: {
179+
values: {
180+
foo: array,
181+
anotherField: 42
182+
}
183+
},
184+
fields: {
185+
'foo[0]': {
186+
name: 'foo[0]',
187+
blur: blur0,
188+
change: change0,
189+
focus: focus0,
190+
touched: true,
191+
error: 'A Error'
192+
},
193+
'foo[1]': {
194+
name: 'foo[1]',
195+
blur: blur1,
196+
change: change1,
197+
focus: focus1,
198+
touched: false,
199+
error: 'B Error'
200+
},
201+
'foo[1].key': {
202+
name: 'foo[1].key',
203+
blur: blur2,
204+
change: change2,
205+
focus: focus2,
206+
touched: false,
207+
error: 'B Error'
208+
},
209+
anotherField: {
210+
name: 'anotherField',
211+
touched: false
212+
}
213+
}
214+
}
215+
const returnValue = remove(['foo', 0], state, { renameField, changeValue })
216+
expect(returnValue).toBeUndefined()
217+
expect(renameField).toHaveBeenCalledTimes(1)
218+
expect(renameField.mock.calls[0][0]).toEqual(state)
219+
expect(renameField.mock.calls[0][1]).toEqual('foo[1].key')
220+
expect(renameField.mock.calls[0][2]).toEqual('foo[0].key')
221+
})
163222
})

0 commit comments

Comments
 (0)