Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions src/remove.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import moveFieldState from './moveFieldState'
const remove: Mutator<any> = (
[name, index]: any[],
state: MutableState<any>,
{ changeValue }: Tools<any>
{ changeValue, renameField }: Tools<any>
) => {
let returnValue
changeValue(state, name, (array: ?(any[])): any[] => {
Expand All @@ -30,7 +30,12 @@ const remove: Mutator<any> = (
// shift all higher ones down
delete state.fields[key]
const decrementedKey = `${name}[${fieldIndex - 1}]${tokens[2]}`
moveFieldState(state, backup.fields[key], decrementedKey, backup)
if (backup.fields[decrementedKey]) {
moveFieldState(state, backup.fields[key], decrementedKey, backup)
} else {
// take care of setting the correct change, blur, focus, validators on new field
renameField(state, key, decrementedKey)
}
}
}
})
Expand Down
59 changes: 59 additions & 0 deletions src/remove.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -160,4 +160,63 @@ describe('remove', () => {
}
})
})

it('should remove value from the specified index, and handle new fields', () => {
const array = ['a', { key: 'val' }]
const changeValue = jest.fn()
const renameField = jest.fn()
function blur0() {}
function change0() {}
function focus0() {}
function blur1() {}
function change1() {}
function focus1() {}
function blur2() {}
function change2() {}
function focus2() {}
const state = {
formState: {
values: {
foo: array,
anotherField: 42
}
},
fields: {
'foo[0]': {
name: 'foo[0]',
blur: blur0,
change: change0,
focus: focus0,
touched: true,
error: 'A Error'
},
'foo[1]': {
name: 'foo[1]',
blur: blur1,
change: change1,
focus: focus1,
touched: false,
error: 'B Error'
},
'foo[1].key': {
name: 'foo[1].key',
blur: blur2,
change: change2,
focus: focus2,
touched: false,
error: 'B Error'
},
anotherField: {
name: 'anotherField',
touched: false
}
}
}
const returnValue = remove(['foo', 0], state, { renameField, changeValue })
expect(returnValue).toBeUndefined()
expect(renameField).toHaveBeenCalledTimes(1)
expect(renameField.mock.calls[0][0]).toEqual(state)
expect(renameField.mock.calls[0][1]).toEqual('foo[1].key')
expect(renameField.mock.calls[0][2]).toEqual('foo[0].key')
})
})