Skip to content
This repository was archived by the owner on Jul 19, 2019. It is now read-only.

[fixed] Reset highlightedIndex when it's outside of items.length #139

Merged
merged 1 commit into from
Jul 19, 2016
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
11 changes: 10 additions & 1 deletion lib/Autocomplete.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,17 @@ let Autocomplete = React.createClass({
this._performAutoCompleteOnKeyUp = false
},

componentWillReceiveProps () {
componentWillReceiveProps (nextProps) {
this._performAutoCompleteOnUpdate = true
// If `items` has changed we want to reset `highlightedIndex`
// since it probably no longer refers to a relevant item
if (this.props.items !== nextProps.items ||
// The entries in `items` may have been changed even though the
// object reference remains the same, double check by seeing
// if `highlightedIndex` points to an existing item
this.state.highlightedIndex >= nextProps.items.length) {
this.setState({ highlightedIndex: null })
}
},

componentDidUpdate (prevProps, prevState) {
Expand Down
15 changes: 15 additions & 0 deletions lib/__tests__/Autocomplete-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,21 @@ describe('Autocomplete acceptance tests', () => {

});

it('should reset `highlightedIndex` when `items` changes', () => {
autocompleteWrapper.setState({ highlightedIndex: 10 });
autocompleteWrapper.setProps({ items: [] });
expect(autocompleteWrapper.state('highlightedIndex')).toBe(null);
});

it('should reset `highlightedIndex` when it falls outside of possible `items` range', () => {
const items = getStates();
autocompleteWrapper.setProps({ items });
autocompleteWrapper.setState({ highlightedIndex: 10 });
items.length = 5;
autocompleteWrapper.setProps({ items });
expect(autocompleteWrapper.state('highlightedIndex')).toBe(null);
});

});

// Event handler unit tests
Expand Down