Skip to content
This repository has been archived by the owner on Dec 23, 2022. It is now read-only.

Commit

Permalink
Fix double elements in on change callback (#247)
Browse files Browse the repository at this point in the history
In case setState was resolved synchronously on change had the new value appended twice
  • Loading branch information
cedrics authored and leMaik committed Nov 26, 2018
1 parent 86dbfe5 commit 48471eb
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 15 deletions.
22 changes: 10 additions & 12 deletions src/ChipInput.js
Original file line number Diff line number Diff line change
Expand Up @@ -337,21 +337,15 @@ class ChipInput extends React.Component {
if (this.props.value && this.props.onAdd) {
this.props.onAdd(chip)
} else {
this.setState({ chips: [ ...this.state.chips, chip ] })
if (this.props.onChange) {
this.props.onChange([ ...this.state.chips, chip ])
}
this.updateChips([ ...this.state.chips, chip ])
}
}
} else if (chip.trim().length > 0) {
if (this.props.allowDuplicates || chips.indexOf(chip) === -1) {
if (this.props.value && this.props.onAdd) {
this.props.onAdd(chip)
} else {
this.setState({ chips: [ ...this.state.chips, chip ] })
if (this.props.onChange) {
this.props.onChange([ ...this.state.chips, chip ])
}
this.updateChips([ ...this.state.chips, chip ])
}
}
} else {
Expand All @@ -375,14 +369,18 @@ class ChipInput extends React.Component {
} else if (this.state.focusedChip > i) {
focusedChip = this.state.focusedChip - 1
}
this.setState({ chips, focusedChip })
if (this.props.onChange) {
this.props.onChange(chips)
}
this.updateChips(chips, { focusedChip })
}
}
}

updateChips (chips, additionalUpdates = {}) {
this.setState({ chips, ...additionalUpdates })
if (this.props.onChange) {
this.props.onChange(chips)
}
}

/**
* Clears the text field for adding new chips.
* @public
Expand Down
7 changes: 4 additions & 3 deletions src/ChipInput.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -386,9 +386,10 @@ describe('blurBehavior modes', () => {
expect(tree.find('input').getDOMNode().value).toBe('')
expect(setTimeout).toHaveBeenCalledTimes(1)

setTimeout(_ => {
expect(tree.find('Chip').map((chip) => chip.text())).toEqual(['a', 'b', 'blur'])
})
expect(handleChange.mock.calls[0][0]).toEqual(['a', 'b', 'blur'])

tree.update()
expect(tree.find('Chip').map((chip) => chip.text())).toEqual(['a', 'b', 'blur'])
})
})

Expand Down

0 comments on commit 48471eb

Please sign in to comment.