diff --git a/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js b/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js index 1f9c5eec4286fa..bd9dc472f94d34 100644 --- a/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js +++ b/packages/material-ui-lab/src/Autocomplete/Autocomplete.test.js @@ -736,6 +736,36 @@ describe('', () => { 'For the input option: "a", `getOptionLabel` returns: undefined', ); }); + + it('warn if getOptionSelected match multiple values for a given option', () => { + const value = [{ id: '10', text: 'One' }, { id: '20', text: 'Two' }]; + const options = [ + { id: '10', text: 'One' }, + { id: '20', text: 'Two' }, + { id: '30', text: 'Three' }, + ]; + + render( + option.text} + getOptionSelected={option => value.find(v => v.id === option.id)} + renderInput={params => } + />, + ); + + fireEvent.keyDown(document.activeElement, { key: 'ArrowDown' }); + fireEvent.keyDown(document.activeElement, { key: 'ArrowDown' }); + fireEvent.keyDown(document.activeElement, { key: 'Enter' }); + + expect(consoleErrorMock.callCount()).to.equal(1); // strict mode renders twice + expect(consoleErrorMock.args()[0][0]).to.include( + 'The component expects a single value to match a given option but found 2 matches.', + ); + }); }); describe('prop: options', () => { diff --git a/packages/material-ui-lab/src/useAutocomplete/useAutocomplete.js b/packages/material-ui-lab/src/useAutocomplete/useAutocomplete.js index c8b32008482e56..9957ed76d7b23c 100644 --- a/packages/material-ui-lab/src/useAutocomplete/useAutocomplete.js +++ b/packages/material-ui-lab/src/useAutocomplete/useAutocomplete.js @@ -439,6 +439,21 @@ export default function useAutocomplete(props) { const item = newValue; newValue = Array.isArray(value) ? [...value] : []; + if (process.env.NODE_ENV !== 'production') { + const matches = newValue.filter(val => getOptionSelected(item, val)); + + if (matches.length > 1) { + console.error( + [ + 'Material-UI: the `getOptionSelected` method of useAutocomplete do not handle the arguments correctly.', + `The component expects a single value to match a given option but found ${ + matches.length + } matches.`, + ].join('\n'), + ); + } + } + const itemIndex = findIndex(newValue, valueItem => getOptionSelected(item, valueItem)); if (itemIndex === -1) {